package com.qujia.station.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.UniversalRedisMessageDto;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.enums.PayTypeEnum;
import com.qujia.common.enums.WxConsumptionMessageEnum;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.DateUtils;
import com.qujia.common.utils.LocalDateTimeUtil;
import com.qujia.common.utils.MathUtil;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.coupon.domain.CouponInfo;
import com.qujia.coupon.domain.CouponUser;
import com.qujia.coupon.mapper.CouponInfoMapper;
import com.qujia.coupon.mapper.CouponUserMapper;
import com.qujia.customer.domain.CustomerCardUseRecord;
import com.qujia.customer.domain.CustomerElectronicCard;
import com.qujia.customer.domain.ReductionActivityBalanceRecord;
import com.qujia.customer.mapper.CustomerCardUseRecordMapper;
import com.qujia.customer.mapper.ReductionActivityBalanceRecordMapper;
import com.qujia.customer.service.ICustomerElectronicCardService;
import com.qujia.enums.integralTypeEnum;
import com.qujia.integral.domain.CustomerPointsRecord;
import com.qujia.integral.mapper.CustomerPointsRecordMapper;
import com.qujia.integral.service.ICustomerPointsRecordService;
import com.qujia.station.controller.RSASignature;
import com.qujia.station.controller.SXFPaySign;
import com.qujia.station.domain.*;
import com.qujia.station.domain.dto.DivideAccountsSettingDto;
import com.qujia.station.domain.dto.DivideSettingDto;
import com.qujia.station.domain.dto.OilSaleNumDto;
import com.qujia.station.domain.dto.RegionalReportDto;
import com.qujia.station.domain.form.PayOrderDetailQueryForm;
import com.qujia.station.domain.form.PayOrderEmployeeQueryForm;
import com.qujia.station.domain.vo.*;
import com.qujia.station.enums.PayTypeNameEnum;
import com.qujia.station.enums.PrintEnum;
import com.qujia.station.mapper.*;
import com.qujia.station.rocketmq.SettleInfoProducer;
import com.qujia.station.service.*;
import com.qujia.station.utils.*;
import com.qujia.system.domain.HttpUtils;
import com.qujia.system.domain.SysRespon;
import com.qujia.system.domain.vo.Base64Util;
import com.qujia.system.domain.vo.CfcaCertUtil;
import com.qujia.system.domain.vo.ParaUtils;
import com.qujia.system.domain.vo.Tools;
import com.qujia.system.jinkong.GatewayRequest;
import com.qujia.system.jinkong.GatewayResponse;
import com.qujia.system.mapper.SysUserMapper;
import com.saobei.open.sdk.DefaultSaobeiApiClient;
import com.saobei.open.sdk.model.requst.trade.SaobeiTradeRefundRequest;
import com.saobei.open.sdk.model.response.trade.SaobeiTradeRefundResponse;
import com.saobei.open.sdk.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

/**
 * 订单支付Service业务层处理
 *
 * @author qujia
 * @date 2020-12-10
 */
@Service
@Slf4j
public class PayOrderServiceImpl implements IPayOrderService {
    public static final LocalDateTime OLD_ACTIVITY_CREATE_TIME = LocalDateTime.of(2023, 8, 5, 0, 0, 0);
    public static final LocalDateTime POS_ORDER_NO_CHANGE_TIME = LocalDateTime.of(2024, 1, 26, 3, 30, 0);

    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private PayOrderHistoryMapper payOrderHistoryMapper;

    @Autowired
    private PayWayMapper payWayMapper;

    @Autowired
    private OilMapper oilMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TradePaymentRecordsDao tradePaymentRecordsMapper;
    @Autowired
    private AppUserInfoMapper appUserInfoMapper;

    @Autowired
    private IStationService stationService;
    @Resource
    private IEnterpriseService enterpriseService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${message.channel}")
    private String channel;

    @Resource
    private IStationDeviceManageService stationDeviceManageService;
//    String private_pfxPath="C:\\Users\\zcs\\Desktop\\商户密钥\\私钥.pfx"; //商户私钥地址
//
//    String public_certPath="C:\\Users\\zcs\\Desktop\\商户密钥\\xdzf_cfca_prd.cer"; //现代支付公钥地址


    String private_pfxPath = "/home/jinkongzhengshu/私钥.pfx"; //商户私钥地址

    String public_certPath = "/home/jinkongzhengshu/xdzf_cfca_prd.cer"; //现代支付公钥地址

    @Value("${qujia.yunHuaRefundUrl}")
    private String yunHuaRefundUrl;

    @Autowired
    private SettleInfoProducer settleInfoProducer;

    @Resource
    private StationMapper stationMapper;

    @Autowired
    private ClassSettlementMapper classSettlementMapper;

    @Resource
    private SettleInfoPushService settleInfoPushService;

    @Resource
    private IPayOrderService payOrderService;
    @Autowired
    private CustomerPointsRecordMapper customerPointsRecordMapper;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private TeamManagementService teamManagementService;

    @Autowired
    private MemberManagementService memberManagementService;

    @Resource
    private PresentAmountRecordMapper presentAmountRecordMapper;

    @Autowired
    private ICustomerElectronicCardService customerElectronicCardService;
    @Resource
    private CustomerCardUseRecordMapper customerCardUseRecordMapper;

    @Autowired
    private ICustomerPointsRecordService customerPointsRecordService;


    @Value("${qujia.yunHuaOrderQueryUrl}")
    private String yunHuaOrderQueryUrl;

    @Resource
    private OrderPrintService orderPrintService;
    @Autowired
    private PresentCouponUserRecordMapper presentCouponUserRecordMapper;

    @Resource
    private CouponUserMapper couponUserMapper;

    @Resource
    private CouponInfoMapper couponInfoMapper;


    @Resource
    private ReductionActivityBalanceRecordMapper reductionActivityBalanceRecordMapper;

    @Resource
    private OrderPayTypeMapper orderPayTypeMapper;
    @Autowired
    private IUnitePayOrderService unitePayOrderService;
    @Autowired
    private IUnitePayOrderRelService unitePayOrderRelService;

    /**
     * 查询订单支付
     *
     * @param orderId 订单支付ID
     * @return 订单支付
     */
    @Override
    public PayOrder selectPayOrderById(Long orderId) {
        return payOrderMapper.selectPayOrderById(orderId);
    }

    @Override
    public void updatePayOrderAmt(Map<String, Object> params) {

        payOrderMapper.updatePayOrderAmt(params);
    }

    @Override
    @Transactional
    public int deletePay(List<Long> list) {
        return payOrderMapper.deletePay(list);
    }

    @Override
    public void addOrderAmountModificationLog(OrderAmountModificationLog log) {
        payOrderMapper.insertOrderAmountModificationLog(log);
    }

    /**
     * 查询订单支付
     *
     * @param orderId 订单支付ID
     * @return 订单支付
     */
    @Override
    public PayOrder selectPayOrderForFeiEById(Long orderId) {
        return payOrderMapper.selectPayOrderForFeiEById(orderId);
    }

    /**
     * 查询订单支付列表
     *
     * @param payOrder 订单支付
     * @return 订单支付
     */
    @Override
    public List<PayOrder> selectPayOrderListUserPaytime(PayOrder payOrder) {
        return payOrderMapper.selectPayOrderListUserPaytime(payOrder);
    }

    @Override
    public List<DivideAccounts> queryDivideAccountsList(DivideAccounts divideAccounts) {
        return payOrderMapper.queryDivideAccountsList(divideAccounts);
    }


    @Override
    public List<DivideAccountsSettingDto> queryDivideSettingList(DivideAccountsSettingDto divideAccountsSettingDto) {

        return payOrderMapper.queryDivideSettingList(divideAccountsSettingDto);
    }

    @Override
    public DivideAccountsDetailVo selectDivideAccountsDetail(String uuid) {
        DivideAccountsDetailVo divideAccountsDetailVo = new DivideAccountsDetailVo();
        List<DivideAccounts> divideAccList = payOrderMapper.selectDivideAccountsDetail(uuid);
        if (divideAccList.size() > 0) {
            divideAccountsDetailVo.setBeginMmo(divideAccList.get(0).getBeginMmo());
            divideAccountsDetailVo.setMaxPercentage(divideAccList.get(0).getMaxPercentage());
            divideAccountsDetailVo.setMmoName(divideAccList.get(0).getMmoName());
            divideAccountsDetailVo.setEnterpriseName(divideAccList.get(0).getEnterpriseName());
            divideAccountsDetailVo.setStationName(divideAccList.get(0).getStationName());
            divideAccountsDetailVo.setDivideAccountsList(divideAccList);
        }
        return divideAccountsDetailVo;
    }

    ;

    @Override
    public int selectDivideSettingStatus(String beginMmo, String status) {
        DivideAccountsSettingDto divideAccountsSettingDto = new DivideAccountsSettingDto();
        divideAccountsSettingDto.setBeginMmo(beginMmo);
        divideAccountsSettingDto.setStatus(status);
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        divideAccountsSettingDto.setUpdateTime(formattedDateTime);
        return payOrderMapper.updateDivideSettingStatus(divideAccountsSettingDto);
    }

    @Override
    public DivideAccountsSettingDto selectDivideSettingDetail(String beginMmo, String stationId) {
        DivideAccountsSettingDto divideAccountsDetailVo = new DivideAccountsSettingDto();
        List<DivideAccountsSettingDto> divideAccList = payOrderMapper.selectDivideSettingDetail(beginMmo, stationId);
        if (divideAccList.size() > 0) {
            divideAccountsDetailVo.setBeginMmo(divideAccList.get(0).getBeginMmo());
            divideAccountsDetailVo.setMaxPercentage(divideAccList.get(0).getMaxPercentage());
            divideAccountsDetailVo.setMmoName(divideAccList.get(0).getMmoName());
            divideAccountsDetailVo.setStationId(divideAccList.get(0).getStationId());
            divideAccountsDetailVo.setStationName(divideAccList.get(0).getStationName());
            divideAccountsDetailVo.setEnterpriseName(divideAccList.get(0).getEnterpriseName());
            List<DivideSettingDto> DivideSettingDtoItem = new ArrayList<>();
            for (DivideAccountsSettingDto divideAccItem : divideAccList) {
                DivideSettingDto divideSettingSinggle = new DivideSettingDto();
                divideSettingSinggle.setMmo(divideAccItem.getMmo());
                divideSettingSinggle.setDivideTxt(divideAccItem.getDivideTxt());
                divideSettingSinggle.setMmoName(divideAccItem.getMmoName());
                divideSettingSinggle.setPercentage(divideAccItem.getPercentage());
                divideSettingSinggle.setStatus(divideAccItem.getSettingType());
                DivideSettingDtoItem.add(divideSettingSinggle);
            }
            divideAccountsDetailVo.setDivideAccountsList(DivideSettingDtoItem);
        }
        return divideAccountsDetailVo;
    }

    ;


    /**
     * 查询订单支付列表
     *
     * @param payOrder 订单支付
     * @return 订单支付
     */
    @Override
    public List<PayOrder> selectPayOrderList(PayOrder payOrder) {
        // 查询支付方式
        OrderPayType orderPayType = new OrderPayType();
        orderPayType.setStationId(payOrder.getStationId());
        orderPayType.setStationIdList(payOrder.getStationIdList());
        List<PayOrder> payOrders = payOrderMapper.selectPayOrderList(payOrder);
        List<OrderPayType> orderPayTypeList = orderPayTypeMapper.selectOrderPayType(orderPayType);
        for (PayOrder order : payOrders) {
            setPayTypeName(order, orderPayTypeList);
        }
        return payOrders;
    }

    @Override
    public AjaxResult creationDivideSetting(DivideAccountsSettingDto divideAccountsSettingDto) {
        Integer mmoCount = payOrderMapper.selectByBeginMmo(divideAccountsSettingDto.getBeginMmo(), divideAccountsSettingDto.getStationId().toString());
        if (mmoCount > 0) {
            return AjaxResult.error("该商户已经设置过了");
        } else {
            List<DivideSettingDto> DivideSettingList = divideAccountsSettingDto.getDivideAccountsList();
            Set<String> mmoSet = new HashSet<>();
            boolean hasDuplicate = false;

            for (DivideSettingDto divideSetting : DivideSettingList) {
                String mmo = divideSetting.getMmo();
                if (mmoSet.contains(mmo)) {
                    hasDuplicate = true;
                    break;
                } else {
                    mmoSet.add(mmo);
                }
            }

            if (hasDuplicate) {
                return AjaxResult.error("分账收款方收款账户重复");
            }

            Station station = stationMapper.selectStationById(divideAccountsSettingDto.getStationId());
            Enterprise enterprise = enterpriseMapper.selectEnterpriseById(station.getEnterpriseId());
            LocalDateTime currentTime = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedTime = currentTime.format(formatter);
            int i = 0;
            if (DivideSettingList != null && DivideSettingList.size() > 0) {
                for (DivideSettingDto DivideSettingItem : DivideSettingList) {
                    DivideAccountsSettingDto item = new DivideAccountsSettingDto();
                    item.setBeginMmo(divideAccountsSettingDto.getBeginMmo());
                    item.setStationId(divideAccountsSettingDto.getStationId());
                    item.setMaxPercentage(divideAccountsSettingDto.getMaxPercentage());
                    item.setStationName(station.getStationName());
                    item.setStatus("1");
                    item.setCreateTime(formattedTime);
                    item.setEnterpriseId(station.getEnterpriseId());
                    item.setEnterpriseName(enterprise.getEnterpriseName());
                    item.setMmo(DivideSettingItem.getMmo());
                    item.setMmoName(DivideSettingItem.getMmoName());
                    item.setDivideTxt(DivideSettingItem.getDivideTxt());
                    item.setSettingType(DivideSettingItem.getStatus());
                    item.setPercentage(DivideSettingItem.getPercentage());

                    payOrderMapper.creationDivideSetting(item);
                    i++;
                }
            }
            return AjaxResult.success();
        }

    }

    @Override
    public AjaxResult deleteByBeginMmo(DivideAccountsSettingDto divideAccountsSettingDto) {
        int a = payOrderMapper.deleteByBeginMmo(divideAccountsSettingDto.getBeginMmo(), divideAccountsSettingDto.getStationId().toString());
        if (a > 0) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }


    @Override
    public AjaxResult updateDivideSetting(DivideAccountsSettingDto divideAccountsSettingDto) {
        List<DivideSettingDto> DivideSettingList = divideAccountsSettingDto.getDivideAccountsList();

        Set<String> mmoSet = new HashSet<>();
        boolean hasDuplicate = false;

        for (DivideSettingDto divideSetting : DivideSettingList) {
            String mmo = divideSetting.getMmo();
            if (mmoSet.contains(mmo)) {
                hasDuplicate = true;
                break;
            } else {
                mmoSet.add(mmo);
            }
        }

        if (hasDuplicate) {
            return AjaxResult.error("分账收款方收款账户重复");
        }
        payOrderMapper.deleteByBeginMmo(divideAccountsSettingDto.getBeginMmo(), divideAccountsSettingDto.getStationId().toString());
        Station station = stationMapper.selectStationById(divideAccountsSettingDto.getStationId());
        Enterprise enterprise = enterpriseMapper.selectEnterpriseById(station.getEnterpriseId());
        String formattedTime = divideAccountsSettingDto.getCreateTime();
        int i = 0;
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        if (DivideSettingList != null && DivideSettingList.size() > 0) {
            for (DivideSettingDto DivideSettingItem : DivideSettingList) {
                DivideAccountsSettingDto item = new DivideAccountsSettingDto();
                item.setBeginMmo(divideAccountsSettingDto.getBeginMmo());
                item.setStationId(divideAccountsSettingDto.getStationId());
                item.setMaxPercentage(divideAccountsSettingDto.getMaxPercentage());
                item.setStationName(station.getStationName());
                item.setStatus(divideAccountsSettingDto.getStatus());
                item.setCreateTime(formattedTime);
                item.setEnterpriseId(station.getEnterpriseId());
                item.setEnterpriseName(enterprise.getEnterpriseName());
                item.setMmo(DivideSettingItem.getMmo());
                item.setMmoName(DivideSettingItem.getMmoName());
                item.setDivideTxt(DivideSettingItem.getDivideTxt());
                item.setSettingType(DivideSettingItem.getStatus());
                item.setPercentage(DivideSettingItem.getPercentage());
                item.setUpdateTime(formattedDateTime);
                payOrderMapper.creationDivideSetting(item);
                i++;
            }
        }
        return AjaxResult.success();

    }


    /**
     * 查询订单支付列表
     *
     * @param payOrder 订单支付
     * @return 订单支付
     */
    @Override
    public List<PayOrder> selectAllPayOrderList(PayOrder payOrder) {
        // 查询支付方式
        OrderPayType orderPayType = new OrderPayType();
        orderPayType.setStationId(payOrder.getStationId());
        orderPayType.setStationIdList(payOrder.getStationIdList());
        List<PayOrder> payOrders = payOrderMapper.selectAllPayOrderList(payOrder);
        List<OrderPayType> orderPayTypeList = orderPayTypeMapper.selectOrderPayType(orderPayType);
        for (PayOrder order : payOrders) {
            setPayTypeName(order, orderPayTypeList);
        }
        return payOrders;
    }

    /**
     * 查询七天内数据
     *
     * @param payOrder 订单支付
     * @return 订单支付
     */
    @Override
    public List<Map<String, Object>> homePaymentSumQuery(PayOrder payOrder) {
        List<Map<String, Object>> dataList = new ArrayList<>();
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDateTime date1;
        try {
            date1 = LocalDateTime.parse(payOrder.getBeginTime(), formatter1);
        } catch (DateTimeParseException e) {
            LocalDate date = LocalDate.parse(payOrder.getBeginTime(), formatter2);
            date1 = date.atStartOfDay();
        }

        LocalDateTime date2;
        try {
            date2 = LocalDateTime.parse(payOrder.getEndTime(), formatter1);
        } catch (DateTimeParseException e) {
            LocalDate date = LocalDate.parse(payOrder.getEndTime(), formatter2);
            date2 = date.atStartOfDay();
        }
        LocalDateTime currentDateTime = LocalDateTime.now(); // 获取当前日期和时间
        LocalDateTime sixDaysAgo = currentDateTime.minusDays(6); // 获取当前日期和时间往前6天的日期和时间


        PayOrder orderitem = new PayOrder();
        PayOrder orderlistother = new PayOrder();


        if (date1.isAfter(sixDaysAgo)) {
            // 开始时间在当前时间往前6天内
            PayOrder orderSeven = payOrderMapper.homePaymentSumQuery(payOrder);
            if (orderSeven != null) {
                orderitem = orderSeven;
            }
        } else {
            PayOrder orderSeven = payOrderMapper.homePaymentSumQuery(payOrder);
            if (orderSeven != null) {
                orderitem = orderSeven;
            }

            PayOrder orderOther = payOrderHistoryMapper.homePaymentSumQuery(payOrder);
            if (orderOther != null) {
                orderlistother = orderOther;
            }


        }
        BigDecimal allbigDecimal = BigDecimal.ZERO;
        BigDecimal wxbigDecimal = orderitem.getWxAmt() != null ? orderitem.getWxAmt() : BigDecimal.ZERO;
        BigDecimal zfbbigDecimal = (orderitem.getZfbAmt() != null) ? orderitem.getZfbAmt() : BigDecimal.ZERO;
        BigDecimal dzkbigDecimal = (orderitem.getDzkAmt() != null) ? orderitem.getDzkAmt() : BigDecimal.ZERO;
        BigDecimal xjbigDecimal = (orderitem.getXjAmt() != null) ? orderitem.getXjAmt() : BigDecimal.ZERO;
        BigDecimal posbigDecimal = (orderitem.getPosAmt() != null) ? orderitem.getPosAmt() : BigDecimal.ZERO;
        BigDecimal cdkBigDecimal = (orderitem.getCdkAmt() != null) ? orderitem.getCdkAmt() : BigDecimal.ZERO;
        BigDecimal stkBigDecimal = (orderitem.getDkqAmt() != null) ? orderitem.getDkqAmt() : BigDecimal.ZERO;
        BigDecimal yhkBigDecimal = (orderitem.getYhkAmt() != null) ? orderitem.getYhkAmt() : BigDecimal.ZERO;

        wxbigDecimal = wxbigDecimal.add((orderlistother.getWxAmt() != null) ? orderlistother.getWxAmt() : BigDecimal.ZERO);

        zfbbigDecimal = zfbbigDecimal.add((orderlistother.getZfbAmt() != null) ? orderlistother.getZfbAmt() : BigDecimal.ZERO);
        dzkbigDecimal = dzkbigDecimal.add((orderlistother.getDzkAmt() != null) ? orderlistother.getDzkAmt() : BigDecimal.ZERO);
        xjbigDecimal = xjbigDecimal.add((orderlistother.getXjAmt() != null) ? orderlistother.getXjAmt() : BigDecimal.ZERO);
        posbigDecimal = posbigDecimal.add((orderlistother.getPosAmt() != null) ? orderlistother.getPosAmt() : BigDecimal.ZERO);
        cdkBigDecimal = cdkBigDecimal.add((orderlistother.getCdkAmt() != null) ? orderlistother.getCdkAmt() : BigDecimal.ZERO);
        stkBigDecimal = stkBigDecimal.add((orderlistother.getDkqAmt() != null) ? orderlistother.getDkqAmt() : BigDecimal.ZERO);
        yhkBigDecimal = yhkBigDecimal.add((orderlistother.getYhkAmt() != null) ? orderlistother.getYhkAmt() : BigDecimal.ZERO);


        allbigDecimal = wxbigDecimal.add(zfbbigDecimal)
                .add(dzkbigDecimal).add(xjbigDecimal).add(posbigDecimal).add(cdkBigDecimal).add(stkBigDecimal).add(yhkBigDecimal);
        BigDecimal hundred = new BigDecimal("100.00");
        BigDecimal wxPercentage = BigDecimal.ZERO;
        BigDecimal zfbPercentage = BigDecimal.ZERO;
        BigDecimal dzkPercentage = BigDecimal.ZERO;
        BigDecimal xjPercentage = BigDecimal.ZERO;
        BigDecimal posPercentage = BigDecimal.ZERO;
        BigDecimal cdkPercentage = BigDecimal.ZERO;
        BigDecimal stkPercentage = BigDecimal.ZERO;
        BigDecimal yhkPercentage = BigDecimal.ZERO;
        if (allbigDecimal.equals(new BigDecimal("0")) || allbigDecimal.equals(new BigDecimal("0.0")) || allbigDecimal.compareTo(BigDecimal.ZERO) == 0) {

        } else {
            wxPercentage = wxbigDecimal.multiply(hundred)
                    .divide(allbigDecimal, 2, RoundingMode.HALF_UP);

            zfbPercentage = zfbbigDecimal.multiply(hundred)
                    .divide(allbigDecimal, 2, RoundingMode.HALF_UP);

            dzkPercentage = dzkbigDecimal.multiply(hundred)
                    .divide(allbigDecimal, 2, RoundingMode.HALF_UP);

            xjPercentage = xjbigDecimal.multiply(hundred)
                    .divide(allbigDecimal, 2, RoundingMode.HALF_UP);

            posPercentage = posbigDecimal.multiply(hundred)
                    .divide(allbigDecimal, 2, RoundingMode.HALF_UP);

            cdkPercentage = cdkBigDecimal.multiply(hundred)
                    .divide(allbigDecimal, 2, BigDecimal.ROUND_HALF_UP);

            stkPercentage = stkBigDecimal.multiply(hundred)
                    .divide(allbigDecimal, 2, BigDecimal.ROUND_HALF_UP);

            yhkPercentage = yhkBigDecimal.multiply(hundred)
                    .divide(allbigDecimal, 2, RoundingMode.HALF_UP);

        }

        Map<String, Object> wxMap = new HashMap<>();
        wxMap.put("name", "微信支付");
        wxMap.put("y", wxPercentage.doubleValue());
        wxMap.put("paycount", wxbigDecimal);
        wxMap.put("color", "#00C889");
        dataList.add(wxMap);

        Map<String, Object> zfbMap = new HashMap<>();
        zfbMap.put("name", "支付宝支付");
        zfbMap.put("y", zfbPercentage.doubleValue());
        zfbMap.put("paycount", zfbbigDecimal);
        zfbMap.put("color", "#0FA2FB");
        dataList.add(zfbMap);

        Map<String, Object> dzkMap = new HashMap<>();
        dzkMap.put("name", "电子卡支付");
        dzkMap.put("y", dzkPercentage.doubleValue());
        dzkMap.put("paycount", dzkbigDecimal);
        dzkMap.put("color", "#FF6B00");
        dataList.add(dzkMap);

        Map<String, Object> cdkMap = new HashMap<>();
        cdkMap.put("name", "车队卡支付");
        cdkMap.put("y", cdkPercentage.doubleValue());
        cdkMap.put("paycount", cdkBigDecimal);
        cdkMap.put("color", "#12d9db");
        dataList.add(cdkMap);

        // 添加实体卡支付
        Map<String, Object> stkMap = new HashMap<>();
        stkMap.put("name", "实体卡支付");
        stkMap.put("y", stkPercentage.doubleValue());
        stkMap.put("paycount", stkBigDecimal);
        stkMap.put("color", "#CCCCCC");
        dataList.add(stkMap);

        Map<String, Object> posMap = new HashMap<>();
        posMap.put("name", "POS机支付");
        posMap.put("y", posPercentage.doubleValue());
        posMap.put("paycount", posbigDecimal);
        posMap.put("color", "#FFD400");
        dataList.add(posMap);

        Map<String, Object> yhkMap = new HashMap<>();
        yhkMap.put("name", "银行卡支付");
        yhkMap.put("y", yhkPercentage.doubleValue());
        yhkMap.put("paycount", yhkBigDecimal);
        yhkMap.put("color", "#FFD400");
        dataList.add(yhkMap);

        Map<String, Object> xjMap = new HashMap<>();
        xjMap.put("name", "现金支付");
        xjMap.put("y", xjPercentage.doubleValue());
        xjMap.put("paycount", xjbigDecimal);
        xjMap.put("color", "#FF2F47");
        dataList.add(xjMap);

        return dataList;
    }

    /**
     * 查询七天内数据
     *
     * @param payOrder 订单支付
     * @return 订单支付
     */
    @Override
    public List<Map<String, Object>> homeSevenSumQuery(PayOrder payOrder, List<ClassSettlementCard> rechargeAmtSeven) {

        LocalDate comparedate1 = LocalDate.now().minusDays(7);
        LocalDate comparedate2 = LocalDate.now().minusDays(6);
        LocalDate comparedate3 = LocalDate.now().minusDays(5);
        LocalDate comparedate4 = LocalDate.now().minusDays(4);
        LocalDate comparedate5 = LocalDate.now().minusDays(3);
        LocalDate comparedate6 = LocalDate.now().minusDays(2);
        LocalDate comparedate7 = LocalDate.now().minusDays(1);
        List<LocalDate> createdList = new ArrayList<>();
        createdList.add(comparedate1);
        createdList.add(comparedate2);
        createdList.add(comparedate3);
        createdList.add(comparedate4);
        createdList.add(comparedate5);
        createdList.add(comparedate6);
        createdList.add(comparedate7);
        payOrder.setCreatedList(createdList);

        List<PayOrder> orderlist3 = payOrderMapper.homeSevenSumQuery(payOrder);

        ZoneId zoneId = ZoneId.of("Asia/Shanghai");
        int daycount1 = 0;
        int daycount2 = 0;
        int daycount3 = 0;
        int daycount4 = 0;
        int daycount5 = 0;
        int daycount6 = 0;
        int daycount7 = 0;
        BigDecimal paycount1 = BigDecimal.ZERO;
        BigDecimal paycount2 = BigDecimal.ZERO;
        BigDecimal paycount3 = BigDecimal.ZERO;
        BigDecimal paycount4 = BigDecimal.ZERO;
        BigDecimal paycount5 = BigDecimal.ZERO;
        BigDecimal paycount6 = BigDecimal.ZERO;
        BigDecimal paycount7 = BigDecimal.ZERO;

        for (PayOrder orderitem3 : orderlist3) {
            LocalDate localDate = orderitem3.getCreatedDate().toInstant().atZone(zoneId).toLocalDateTime().toLocalDate();

            BigDecimal amt2 = orderitem3.getAmt();
            if (localDate.equals(comparedate1)) {
                daycount1 = orderitem3.getOrderCount();
                paycount1 = paycount1.add(amt2);

            }
            if (localDate.equals(comparedate2)) {
                daycount2 = orderitem3.getOrderCount();
                paycount2 = paycount2.add(amt2);
            }
            if (localDate.equals(comparedate3)) {
                daycount3 = orderitem3.getOrderCount();
                paycount3 = paycount3.add(amt2);
            }
            if (localDate.equals(comparedate4)) {
                daycount4 = orderitem3.getOrderCount();
                paycount4 = paycount4.add(amt2);
            }
            if (localDate.equals(comparedate5)) {
                daycount5 = orderitem3.getOrderCount();
                paycount5 = paycount5.add(amt2);
            }
            if (localDate.equals(comparedate6)) {
                daycount6 = orderitem3.getOrderCount();
                paycount6 = paycount6.add(amt2);
            }
            if (localDate.equals(comparedate7)) {
                daycount7 = orderitem3.getOrderCount();
                paycount7 = paycount7.add(amt2);
            }
        }
        for (ClassSettlementCard rechargeAmt : rechargeAmtSeven) {
            LocalDate localDate = rechargeAmt.getCreateTime().toInstant().atZone(zoneId).toLocalDateTime().toLocalDate();
            BigDecimal amt2 = rechargeAmt.getAmt() != null ? rechargeAmt.getAmt() : BigDecimal.ZERO;
            if (localDate.equals(comparedate1)) {
                paycount1 = paycount1.add(amt2);
            }
            if (localDate.equals(comparedate2)) {
                paycount2 = paycount2.add(amt2);
            }
            if (localDate.equals(comparedate3)) {
                paycount3 = paycount3.add(amt2);
            }
            if (localDate.equals(comparedate4)) {
                paycount4 = paycount4.add(amt2);
            }
            if (localDate.equals(comparedate5)) {
                paycount5 = paycount5.add(amt2);
            }
            if (localDate.equals(comparedate6)) {
                paycount6 = paycount6.add(amt2);
            }
            if (localDate.equals(comparedate7)) {
                paycount7 = paycount7.add(amt2);
            }
        }
        List<Integer> transactionCounts = Arrays.asList(daycount1, daycount2, daycount3, daycount4, daycount5, daycount6, daycount7);
        List<BigDecimal> transactionAmounts = Arrays.asList(paycount1, paycount2, paycount3, paycount4, paycount5, paycount6, paycount7);
        List<Map<String, Object>> series = new ArrayList<>();
        Map<String, Object> countMap = new HashMap<>();
        countMap.put("name", "交易笔数");
        countMap.put("color", "#FF6B00");
        countMap.put("data", transactionCounts);
        series.add(countMap);

        Map<String, Object> amountMap = new HashMap<>();
        amountMap.put("name", "交易金额");
        amountMap.put("color", "#FFD400");
        amountMap.put("data", transactionAmounts);
        amountMap.put("yAxis", 1);
        series.add(amountMap);

        return series;
    }


    /**
     * 查询订单统计量
     *
     * @param payOrder 订单支付
     * @return 订单支付集合
     */
    @Override
    public List<StatisticsPayOrder> selectStatisticsPayOrderList(PayOrder payOrder) {
        return payOrderMapper.selectStatisticsPayOrderList(payOrder);
    }


    /**
     * 查询订单合计信息
     *
     * @param payOrder 订单支付
     * @return 订单支付集合
     */
    @Override
    public StatisticsPayOrder selectStatisticsPayOrderSum(PayOrder payOrder) {
        return payOrderMapper.selectStatisticsPayOrderSum(payOrder);
    }

    /**
     * 小程序查询汇总订单
     *
     * @param payOrder 订单支付
     * @return 汇总信息
     */
    public PayOrder selectAppletPayOrderSum(PayOrder payOrder) {
        return payOrderMapper.selectAppletPayOrderSum(payOrder);
    }

    /**
     * 新增订单支付
     *
     * @param payOrder 订单支付
     * @return 结果
     */
    @Override
    public int insertPayOrder(PayOrder payOrder) {
        return payOrderMapper.insertPayOrder(payOrder);
    }

    private String generateOrdNo() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        String ordNo = System.currentTimeMillis() + result;
        return ordNo;
    }

    /**
     * 新增订单支付
     *
     * @param payOrder 订单支付
     * @return 结果
     */
    @Override
    public AjaxResult insertPayOrderForStar(PayOrder payOrder) {
        String ordNo = generateOrdNo();
        payOrder.setOrderNo(ordNo);
        payOrder.setUtmSource("2");//2为来源繁星
        Oil oil = oilMapper.selectOilByName(payOrder.getOilName());
        if (oil != null) {
            payOrder.setOilName(oil.getOilId().toString());
        }
        SysUser sysuser = sysUserMapper.selectUserByStationeId(payOrder.getStationId());
        if (sysuser != null) {
            payOrder.setOilPersonnelId(sysuser.getUserId().toString());
        }
        int a = payOrderMapper.insertPayOrderForStar(payOrder);
        //打印小票
        printStarOrder(payOrder, sysuser);
        if (a > 0) {
            return AjaxResult.success("成功", ordNo);
        } else {
            return AjaxResult.error("新增失败");
        }


    }

    private AjaxResult printStarOrder(PayOrder payOrder, SysUser sysUser) {
        try {

            StationDeviceManage stationDeviceManage = new StationDeviceManage();
            stationDeviceManage.setStationId(payOrder.getStationId());
            stationDeviceManage.setDeviceType("3");
            List<StationDeviceManage> stationDeviceManages = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
            if (stationDeviceManages == null || stationDeviceManages.size() <= 0) {
                return AjaxResult.error("当前站点没有打印机");
            }
            StringBuilder content = new StringBuilder();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            boolean guKeFlag = true;
            boolean shangHuflag = true;
            if ("1".equals(stationDeviceManages.get(0).getPrintType())) {
                shangHuflag = false;
            }
            if ("2".equals(stationDeviceManages.get(0).getPrintType())) {
                guKeFlag = false;
            }
            //不需要补打顾客联订单
            if (guKeFlag) {
                content.append("--------顾客联--------<BR>");
                if (payOrder.getReceivableAmt() != null) {
                    content.append("<BOLD><B>原价：" + payOrder.getReceivableAmt() + "元</B></BOLD><BR>");
                }
                if (StringUtils.isNotBlank(payOrder.getOrderNo())) {
                    content.append("订单号：" + payOrder.getOrderNo() + "<BR>");
                }

                if (payOrder.getAmt() != null) {
                    content.append("实付款：" + payOrder.getAmt() + "<BR>");
                }

                if (payOrder.getReceivableAmt() != null) {
                    content.append("应收款：" + payOrder.getReceivableAmt() + "<BR>");
                }


                String phone = StringUtils.isNotBlank(payOrder.getCustomerPhone()) ? payOrder.getCustomerPhone() : "不详";
                content.append("手机号：" + phone + "<BR>");

                if (StringUtils.isNotBlank(payOrder.getPayType())) {
                    if ("wx".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "微信" + "<BR>");
                    } else if ("zfb".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "支付宝" + "<BR>");
                    } else if ("yl".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "银联" + "<BR>");
                    } else if ("xj".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "现金" + "<BR>");
                    } else if ("dzk".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "电子卡" + "<BR>");
                    } else if ("hyk".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "实体卡" + "<BR>");
                    }

                }

                if (payOrder.getCreatedDate() != null) {
                    content.append("下单时间：" + sdf.format(payOrder.getCreatedDate()) + "<BR>");
                }

                if (payOrder.getPayDate() != null) {
                    content.append("付款时间：" + sdf.format(payOrder.getPayDate()) + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getOilGun())) {
                    content.append("油枪：" + payOrder.getOilGun() + "号枪<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getOilName())) {
                    content.append("油品：" + payOrder.getOilName() + "<BR>");
                }
                if (StringUtils.isNotBlank(payOrder.getOrderLiters() + "")) {
                    content.append("升数：" + payOrder.getOrderLiters() + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getOilPirce() + "")) {
                    content.append("价格：" + payOrder.getOilPirce() + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getStationName())) {
                    content.append("油站：" + payOrder.getStationName() + "<BR>");
                }

                if (Objects.nonNull(sysUser.getUserId())) {
                    content.append("加油员：" + sysUser.getUserName() + "<BR>");
                }

                content.append("-------------------------<BR>");
                content.append("<BR>");
            }
            if (shangHuflag) {
                content.append("--------商户联-------<BR>");
                if (payOrder.getReceivableAmt() != null) {
                    content.append("<BOLD><B>原价：" + payOrder.getReceivableAmt() + "元</B></BOLD><BR>");
                }
                if (StringUtils.isNotBlank(payOrder.getOrderNo())) {
                    content.append("订单号：" + payOrder.getOrderNo() + "<BR>");
                }

                if (payOrder.getAmt() != null) {
                    content.append("实付款：" + payOrder.getAmt() + "<BR>");
                }

                if (payOrder.getReceivableAmt() != null) {
                    content.append("应收款：" + payOrder.getReceivableAmt() + "<BR>");
                }

                if ("2".equals(payOrder.getUtmSource())) {
                    String phone = StringUtils.isNotBlank(payOrder.getCustomerPhone()) ? payOrder.getCustomerPhone() : "不详";
                    content.append("手机号：" + phone + "<BR>");

                } else if (StringUtils.isNotBlank(payOrder.getCustomerPhone())) {
                    content.append("手机号：" + payOrder.getCustomerPhone().replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2") + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getPayType())) {
                    if ("wx".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "微信" + "<BR>");
                    } else if ("zfb".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "支付宝" + "<BR>");
                    } else if ("yl".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "银联" + "<BR>");
                    } else if ("xj".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "现金" + "<BR>");
                    } else if ("dzk".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "电子卡" + "<BR>");
                    } else if ("hyk".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "实体卡" + "<BR>");
                    } else if ("cdk".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "车队卡" + "<BR>");
                    }

                }
                if (payOrder.getCreatedDate() != null) {
                    content.append("下单时间：" + sdf.format(payOrder.getCreatedDate()) + "<BR>");
                }

                if (payOrder.getPayDate() != null) {
                    content.append("付款时间：" + sdf.format(payOrder.getPayDate()) + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getOilGun())) {
                    content.append("油枪：" + payOrder.getOilGun() + "号枪<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getOilName())) {
                    content.append("油品：" + payOrder.getOilName() + "<BR>");
                }
                if (StringUtils.isNotBlank(payOrder.getOrderLiters() + "")) {
                    content.append("升数：" + payOrder.getOrderLiters() + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getOilPirce() + "")) {
                    content.append("价格：" + payOrder.getOilPirce() + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getStationName())) {
                    content.append("油站：" + payOrder.getStationName() + "<BR>");
                }

                if (Objects.nonNull(sysUser.getUserId())) {
                    content.append("加油员：" + sysUser.getUserName() + "<BR>");
                }
                content.append("-------------------------<BR>");
                content.append("<BR>");
            }
            content.append("<BR>");
            content.append("<BR>");

            StationDeviceManage stationDeviceManagerRes;

            try {
                //筛选绑定了用户的小票机
                List<StationDeviceManage> manageWithUser = new ArrayList<>();
                if (payOrder != null && payOrder.getOilPersonnelId() != null && !"".equals(payOrder.getOilPersonnelId())) {
                    manageWithUser = stationDeviceManages.stream().filter(device -> {
//                        if (StringUtils.isNotBlank(device.getUserIds())) {
//                            List<String> userIdsList = Arrays.asList(device.getUserIds().split(","));
//                            return userIdsList.contains(payOrder.getOilPersonnelId());
//                        }
                        if (StationDeviceManage.bindingType_staff.equals(device.getBindingType())) {
                            //当设备选择绑定员工，但未选择指定员工时，设备需播报或打印该设备所绑定的油站的所有订单
                            if (StringUtils.isBlank(device.getUserIds())) {
                                return true;
                            } else {
                                //当设备选择绑定员工且选择了指定的员工时，设备仅播报或打印所绑定员工的订单
                                List<String> userIdsList = Arrays.asList(device.getUserIds().split(","));
                                return userIdsList.contains(payOrder.getOilPersonnelId());
                            }
                        } else if (StationDeviceManage.bindingType_gun.equals(device.getBindingType())) {
                            //当设备选择绑定油枪时，但未选择指定油枪时，设备需播报或打印该设备所绑定的油站的所有订单
                            if (StringUtils.isBlank(device.getGunNo())) {
                                return true;
                            } else {
                                //当设备选择绑定油枪时且选择了指定油枪时，设备仅播报或打印所绑定油枪的订单
                                List<String> gunNoList = Arrays.asList(device.getGunNo().split(","));
                                return gunNoList.contains(payOrder.getOilGun());
                            }
                        }
                        return false;
                    }).collect(Collectors.toList());
                }
                stationDeviceManagerRes = CollectionUtils.isNotEmpty(manageWithUser) ? manageWithUser.get(0) : stationDeviceManages.get(0);
                log.info("筛选绑定用户的小票机信息：{}", stationDeviceManagerRes);
            } catch (Exception e) {
                stationDeviceManagerRes = stationDeviceManages.get(0);
                log.error(e.getMessage());
            }

            String audio = stationDeviceManagerRes.getAudio();
            log.info("自定义语音audio:{}", audio);

            log.info("最终小票机信息：{}", stationDeviceManagerRes);
            String deviceFactory = stationDeviceManagerRes.getDeviceFactory();
            PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
            String printRes = "";
            AjaxResult ajaxResult = AjaxResult.success();
            switch (printEnum) {
                case YILIANYUN:
                    ajaxResult = YiLianYunPrinterUtil.print(content.toString(), stationDeviceManagerRes, payOrder);
                    break;
                case FEIE:
                    String result = FeiEPrinterUtil.printReceipt(stationDeviceManages.get(0).getDeviceNo(), content.toString());
                    org.json.JSONObject resJson = new org.json.JSONObject(result);
                    if ("ok".equals(resJson.get("msg"))) {
                        printRes = "补打小票成功";
                        ajaxResult = AjaxResult.success(printRes);
                    } else {
                        printRes = "补打小票失败";
                        ajaxResult = AjaxResult.error(printRes);
                    }

                    break;
                default:
                    log.info("没有配置小票机，打印失败");
                    break;
            }

            int i = (int) ajaxResult.get("code");
            if (i == 200) {
                payOrderService.updatePayOrderPrintStatus(payOrder.getOrderNo());
            }

            return ajaxResult;
//
//            FeiEPrinterUtil.printReceipt(stationDeviceManages.get(0).getDeviceNo(), content.toString());
//            return AjaxResult.success("打印成功");
        } catch (Exception e) {
            log.error(">pushConsumeToUser", e);
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 修改订单支付
     *
     * @param payOrder 订单支付
     * @return 结果
     */
    @Override
    public int updatePayOrder(PayOrder payOrder) {
        return payOrderMapper.updatePayOrder(payOrder);
    }

    @Override
    public int updatePayOrderByOrderNo(PayOrder payOrder) {

        String utm = payOrderMapper.selectPayOrderByOrderNo(payOrder);
        if (utm == null || !utm.equals("2")) {
            // 当utm为空或不等于2时执行的代码
            String utm2 = payOrderHistoryMapper.selectPayOrderByOrderNo(payOrder);
            if (utm2 == null || !utm2.equals("2")) {
                return 0;
            }
        }

        payOrder.setUtmSource("2");//2为来源繁星
        Oil oil = oilMapper.selectOilByName(payOrder.getOilName());
        if (oil != null) {
            payOrder.setOilName(oil.getOilId().toString());
        }
        SysUser sysuser = sysUserMapper.selectUserByStationeId(payOrder.getStationId());
        if (sysuser != null) {
            payOrder.setOilPersonnelId(sysuser.getUserId().toString());
        }

        int a = payOrderMapper.updatePayOrderByOrderNo(payOrder);
        int b = payOrderHistoryMapper.updatePayOrderByOrderNo(payOrder);

        return a + b;
    }

    /**
     * 批量删除订单支付
     *
     * @param orderIds 需要删除的订单支付ID
     * @return 结果
     */
    @Override
    public int deletePayOrderByIds(Long[] orderIds) {
        return payOrderMapper.deletePayOrderByIds(orderIds);
    }

    /**
     * 删除订单支付信息
     *
     * @param orderId 订单支付ID
     * @return 结果
     */
    @Override
    public int deletePayOrderById(Long orderId) {
        return payOrderMapper.deletePayOrderById(orderId);
    }

    /**
     * 汇总今天的数据
     *
     * @param payOrder
     * @return
     */
    @Override
    public PayOrder selectDaySources(PayOrder payOrder) {
        return payOrderMapper.selectDaySources(payOrder);
    }

    /**
     * 汇总今天所有的信息
     *
     * @param payOrder
     * @return
     */
    @Override
    public PayOrder selectAllDaySources(PayOrder payOrder) {
        return payOrderMapper.selectAllDaySources(payOrder);
    }

    /***
     * 获取数据
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> selectOilTypeSources(PayOrder payOrder) {
        return payOrderMapper.selectOilTypeSources(payOrder);
    }

    /***
     * 获取油品的全部数据
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> selectAllOilTypeSources(PayOrder payOrder) {
        return payOrderMapper.selectAllOilTypeSources(payOrder);
    }

    /**
     * 数据概览，获取数据
     *
     * @param payOrder
     * @return
     */

    @Override
    public PayOrder selectOverViewData(PayOrder payOrder) {
        return payOrderMapper.selectOverViewData(payOrder);
    }

    /**
     * 数据概览，获取数据(包括已经退款的)
     *
     * @param payOrder
     * @return
     */

    @Override
    public PayOrder selectAllOverViewData(PayOrder payOrder) {
        return payOrderMapper.selectAllOverViewData(payOrder);
    }

    /**
     * 月报数据
     *
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> selectDayReport(PayOrder payOrder) {
        return payOrderMapper.selectDayReport(payOrder);
    }

    /**
     * 月报数据（包括已经退款的）
     *
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> selectAllDayReport(PayOrder payOrder) {
        return payOrderMapper.selectAllDayReport(payOrder);
    }

    /**
     * 用于历史数据日报
     * 月报数据(包括已经退款的)
     *
     * @param payOrder
     * @return
     */
    public List<PayOrder> selectNewAllDayReport(PayOrder payOrder) {
        return payOrderMapper.selectNewAllDayReport(payOrder);
    }

    /**
     * 日报折线图获取油品数据
     *
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> listQydata(PayOrder payOrder) {
        return payOrderMapper.listQydata(payOrder);
    }

    /**
     * 获取x轴数据
     *
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> listXdata(PayOrder payOrder) {
        return payOrderMapper.listXdata(payOrder);
    }

    /**
     * 查询导出信息
     *
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> selectPayOrderExport(PayOrder payOrder) {
        return payOrderMapper.selectPayOrderExport(payOrder);
    }

    @Override
    public List<PayOrder> selectLNGPayOrderExport(PayOrder payOrder) {
        return payOrderMapper.selectLNGPayOrderExport(payOrder);
    }

    /**
     * 查询数据，根据员工汇总数据
     *
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> selectPersonnelStructure(PayOrder payOrder) {
        return payOrderMapper.selectPersonnelStructure(payOrder);
    }

    /**
     * 初始化数据班结数据，根据油品汇总
     *
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> selectOilStructure(PayOrder payOrder) {
        return payOrderMapper.selectOilStructure(payOrder);
    }

    /**
     * 初始化数据班结数据，根据员工/支付方式汇总
     *
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> selectPersonnelPayStructure(PayOrder payOrder) {
        return payOrderMapper.selectPersonnelPayStructure(payOrder);
    }

    /**
     * 查询本站第一笔订单
     *
     * @param payOrder
     * @return
     */
    @Override
    public PayOrder getPayOrderInfoMin(PayOrder payOrder) {
        return payOrderMapper.getPayOrderInfoMin(payOrder);
    }


    /**
     * 日报数据汇总
     *
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> dayOilTypeSources(PayOrder payOrder) {
        return payOrderMapper.dayOilTypeSources(payOrder);
    }

    /**
     * 日报数据汇总（包括已经退款的）
     *
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> dayAllOilTypeSources(PayOrder payOrder) {
        return payOrderMapper.dayAllOilTypeSources(payOrder);
    }

    @Override
    public List<PayOrder> LNGDeptList(PayOrder payOrder) {
        return payOrderMapper.LNGDeptList(payOrder);
    }

    /**
     * 关联用户查询订单支付列表
     *
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> selectUserPayOrderList(PayOrder payOrder) {
        return payOrderMapper.selectUserPayOrderList(payOrder);
    }

    /**
     * 通过油品统计信息
     *
     * @param oilPayOrderSum 订单支付
     * @return 订单支付集合
     */
    public List<OilPayOrderSum> selectOilPayOrderSum(PayOrder oilPayOrderSum) {

        if (Objects.nonNull(oilPayOrderSum) && StringUtils.isNotBlank(oilPayOrderSum.getHistoryFlag())
                && "1".equals(oilPayOrderSum.getHistoryFlag())) {
            //2023-09-19 00:00:00
            String nowDayTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", DateUtils.getTodayStartTime());
            oilPayOrderSum.setNowDayTime(nowDayTime);
        }
        return payOrderMapper.selectOilPayOrderSum(oilPayOrderSum);
    }

    /**
     * 通过油品统计信息
     *
     * @param payOrder 订单支付
     * @return 订单支付集合
     */
    public OilPayOrderSum selectOilPayOrderAllSum(PayOrder payOrder) {
        if (Objects.nonNull(payOrder) && StringUtils.isNotBlank(payOrder.getHistoryFlag())
                && "1".equals(payOrder.getHistoryFlag())) {
            //2023-09-19 00:00:00
            String nowDayTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", DateUtils.getTodayStartTime());
            payOrder.setNowDayTime(nowDayTime);
        }

        return payOrderMapper.selectOilPayOrderAllSum(payOrder);
    }

    /**
     * 查询订单支付
     *
     * @param merchantsNumber 订单支付ID
     * @return 订单支付
     */
    public PayOrder selectOrderInfoByMerchantsNumber(String merchantsNumber) {
        return payOrderMapper.selectOrderInfoByMerchantsNumber(merchantsNumber);
    }

    @Override
    public List<PayOrderEmployeeQueryVo> payOrderEmployeeList(PayOrderEmployeeQueryForm payOrderEmployeeQueryForm) {
        if (StringUtils.isEmpty(payOrderEmployeeQueryForm.getBeginTime()) || StringUtils.isEmpty(payOrderEmployeeQueryForm.getEndTime()))
            throw new CustomException("请选择查询的时间段！");



        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate beginDate = LocalDate.parse(payOrderEmployeeQueryForm.getBeginTime(), df);
        LocalDate now = LocalDate.now();
        int days = Period.between(beginDate, now).getDays();
        // 7天之前的联表查询
        List<PayOrderEmployeeQueryVo> payOrderEmployeeQueryVoList;
        log.info("payOrderEmployeeList 请求参数：[{}]", JSONObject.toJSONString(payOrderEmployeeQueryForm));
        if (days < 7) {
            payOrderEmployeeQueryVoList = payOrderMapper.selectPayOrderEmployeeList(payOrderEmployeeQueryForm);
        } else {
            payOrderEmployeeQueryVoList = payOrderMapper.selectAllPayOrderEmployeeList(payOrderEmployeeQueryForm);
        }
        return payOrderEmployeeQueryVoList;
    }

    @Override
    public PayOrderEmployeeQueryVo payOrderEmployeeStatistics(PayOrderEmployeeQueryForm payOrderEmployeeQueryForm) {
        if (StringUtils.isEmpty(payOrderEmployeeQueryForm.getBeginTime()) || StringUtils.isEmpty(payOrderEmployeeQueryForm.getEndTime()))
            throw new CustomException("请选择查询的时间段！");

        SysUser user = SecurityUtils.getLoginUser().getUser();
        String userLevel = user.getUserLevel();
        if (StringUtils.equals(UserConstants.LEVEL_TWO, userLevel)) {  //油企
            payOrderEmployeeQueryForm.setEnterpriseId(user.getEnterpriseId());
        } else if (StringUtils.equals(UserConstants.LEVEL_THREE, userLevel)) {  //油站
            if (StaffUtil.isStaff(user)) {
                payOrderEmployeeQueryForm.setOilPersonnelId(user.getUserId());
            } else {
                payOrderEmployeeQueryForm.setStationId(user.getStationId());
            }
        }
        if (SecurityUtils.isPartner()) {

                EnterpriseAndStationVo itemIds = stationService.getItemIds(user);
                payOrderEmployeeQueryForm.setStationIds(itemIds.getStationIds());


        }

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate beginDate = LocalDate.parse(payOrderEmployeeQueryForm.getBeginTime(), df);
        LocalDate now = LocalDate.now();
        int days = Period.between(beginDate, now).getDays();
        // 7天之前的联表查询
        PayOrderEmployeeQueryVo payOrderEmployeeQueryVo = new PayOrderEmployeeQueryVo();
        log.info("payOrderEmployeeStatistics 请求参数：[{}]", JSONObject.toJSONString(payOrderEmployeeQueryForm));
        if (days < 7) {
            payOrderEmployeeQueryVo = payOrderMapper.selectPayOrderEmployeeStatistics(payOrderEmployeeQueryForm);
        } else {
            PayOrderEmployeeQueryVo newPayOrderEmployeeQueryVo = payOrderMapper.selectPayOrderEmployeeStatistics(payOrderEmployeeQueryForm);
            PayOrderEmployeeQueryVo oldPayOrderEmployeeQueryVo = payOrderHistoryMapper.selectPayOrderEmployeeStatistics(payOrderEmployeeQueryForm);
            if (Objects.isNull(newPayOrderEmployeeQueryVo)) {
                payOrderEmployeeQueryVo = oldPayOrderEmployeeQueryVo;
            } else if (Objects.nonNull(oldPayOrderEmployeeQueryVo)) {
                newPayOrderEmployeeQueryVo.setCount((Objects.nonNull(newPayOrderEmployeeQueryVo.getCount()) ? newPayOrderEmployeeQueryVo.getCount() : 0)
                        + (Objects.nonNull(oldPayOrderEmployeeQueryVo.getCount()) ? oldPayOrderEmployeeQueryVo.getCount() : 0));
                newPayOrderEmployeeQueryVo.setTotal((Objects.nonNull(newPayOrderEmployeeQueryVo.getTotal()) ? newPayOrderEmployeeQueryVo.getTotal() : BigDecimal.ZERO)
                        .add(Objects.nonNull(oldPayOrderEmployeeQueryVo.getTotal()) ? oldPayOrderEmployeeQueryVo.getTotal() : BigDecimal.ZERO));
                payOrderEmployeeQueryVo = newPayOrderEmployeeQueryVo;
            }
        }
        return payOrderEmployeeQueryVo;
    }

    @Override
    public List<PayOrderDetailQueryVo> payOrderDetailList(PayOrderDetailQueryForm payOrderDetailQueryForm) {
        if (StringUtils.isEmpty(payOrderDetailQueryForm.getBeginTime()) || StringUtils.isEmpty(payOrderDetailQueryForm.getEndTime()))
            throw new CustomException("查询的时间段不能为空！");
        if (ObjectUtils.isEmpty(payOrderDetailQueryForm.getOilPersonnelId()))
            throw new CustomException("加油员id不能为空！");

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate beginDate = LocalDate.parse(payOrderDetailQueryForm.getBeginTime(), df);
        LocalDate now = LocalDate.now();
        int days = Period.between(beginDate, now).getDays();
        // 7天之前的联表查询
        List<PayOrderDetailQueryVo> payOrderDetailQueryVoList;
        if (days < 7) {
            payOrderDetailQueryVoList = payOrderMapper.selectPayOrderDetailList(payOrderDetailQueryForm);
        } else {
            payOrderDetailQueryVoList = payOrderMapper.selectAllPayOrderDetailList(payOrderDetailQueryForm);
        }
        SysUser user = sysUserMapper.selectUserById(payOrderDetailQueryForm.getOilPersonnelId());

        OrderPayType orderPayType = new OrderPayType();
        orderPayType.setStationId(user.getStationId());
        List<OrderPayType> orderPayTypeList = orderPayTypeMapper.selectOrderPayType(orderPayType);
        for (PayOrderDetailQueryVo payOrderDetailQueryVo : payOrderDetailQueryVoList) {
            setPayTypeName(payOrderDetailQueryVo, orderPayTypeList);
        }
        return payOrderDetailQueryVoList;
    }

    // 匹配支付方式
    private void setPayTypeName(PayOrderDetailQueryVo payOrderDetailQueryVo, List<OrderPayType> orderPayTypeList) {
        String payTypeName = PayTypeNameEnum.getPayTypeName(payOrderDetailQueryVo.getPayType());
        if (StringUtils.isNotBlank(payTypeName)) {
            payOrderDetailQueryVo.setPayTypeName(payTypeName);
        }

        for (OrderPayType orderPayType : orderPayTypeList) {
            if (orderPayType.getPayType().equals(payOrderDetailQueryVo.getPayType())) {
                payOrderDetailQueryVo.setPayTypeName(orderPayType.getPayTypeName());
            }
        }
    }

    @Override
    public void updatePayOrderPrintStatus(String orderNo) {
        payOrderMapper.updatePayOrderPrintStatus(orderNo);

    }

    @Override
    public List<PayOrder> selectCdkPayOrderList(PayOrder payOrder) {
        return payOrderMapper.selectCdkPayOrderList(payOrder);
    }

    @Override
    public List<PayOrder> selectNewCdkPayOrderList(PayOrder payOrder) {
        List<PayOrder> newPayOrderList = payOrderMapper.selectNewCdkPayOrderList(payOrder);
        List<PayOrder> oldPayOrderList = payOrderMapper.selectOldCdkPayOrderList(payOrder);
        newPayOrderList.addAll(oldPayOrderList);
        for (PayOrder order : newPayOrderList) {
            setCustomerName(order);
        }
        return newPayOrderList;
    }

    private void setCustomerName(PayOrder order) {
        if (Objects.nonNull(order.getEnterpriseId()) && Objects.nonNull(order.getCustomerPhone())) {
            SysAppUserInfo appUserInfo = new SysAppUserInfo();
            appUserInfo.setStationId(order.getEnterpriseId());
            appUserInfo.setMobilePhone(order.getCustomerPhone());
            SysAppUserInfo sysAppUserInfo = appUserInfoMapper.getOne(appUserInfo);
            order.setCustomerName(Objects.nonNull(sysAppUserInfo) ? sysAppUserInfo.getBlogNickName() : null);
        }
    }

    @Override
    public List<PayOrder> selectCdkPayHisOrderList(PayOrder payOrder) {
        return payOrderMapper.selectCdkPayHisOrderList(payOrder);
    }

    @Override
    public List<PayOrder> selectPayOrderAndHisPayOrderList(PayOrder payOrder) {
        return payOrderMapper.selectPayOrderAndHisPayOrderList(payOrder);
    }

    @Override
    public List<StatisticsPayOrder> newSelectStatisticsPayOrderList(PayOrder payOrder) {
        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user = current.getUser();
        //判断用户等级进行赋值
        assignPayOrder(payOrder, user);
        payOrder.setStatus("1");
        List<StatisticsPayOrder> statisticsPayOrders = payOrderMapper.newSelectStatisticsPayOrderList(payOrder);
        List<StatisticsPayOrder> SevenPayOrders = payOrderHistoryMapper.newSelectStatisticsPayOrderHistoryList(payOrder);
        //将历史订单也查出合在一起
        statisticsPayOrders.addAll(SevenPayOrders);
        Map<Long, List<StatisticsPayOrder>> payOrderMap = statisticsPayOrders.stream().collect(Collectors.groupingBy(StatisticsPayOrder::getStationId));
        ArrayList<StatisticsPayOrder> statisticsPayOrdersVo = new ArrayList<>();

        for (Long stationId : payOrderMap.keySet()) {
            BigDecimal amt = new BigDecimal("0.00");
            BigDecimal orderLiters = new BigDecimal("0.00");
            BigDecimal receivableAmt = new BigDecimal("0.00");
            BigDecimal receivedAmt = new BigDecimal("0.00");
            BigDecimal discountAmt = new BigDecimal("0.00");
            Integer countNum = 0;

            StatisticsPayOrder statistAllPayOrder = new StatisticsPayOrder();

            for (StatisticsPayOrder statisticsPayOrder : payOrderMap.get(stationId)) {
                amt = amt.add(statisticsPayOrder.getAmt());
                orderLiters = orderLiters.add(statisticsPayOrder.getOrderLiters());
                receivableAmt = receivableAmt.add(statisticsPayOrder.getReceivableAmt());
                receivedAmt = receivedAmt.add(statisticsPayOrder.getReceivedAmt());
                discountAmt = discountAmt.add(statisticsPayOrder.getDiscountAmt());
                countNum += statisticsPayOrder.getCountNum();

                statistAllPayOrder.setEnterpriseName(statisticsPayOrder.getEnterpriseName());
                statistAllPayOrder.setStationName(statisticsPayOrder.getStationName());
                statistAllPayOrder.setEnterpriseId(statisticsPayOrder.getEnterpriseId());
                statistAllPayOrder.setStationId(statisticsPayOrder.getStationId());
            }

            statistAllPayOrder.setAmt(amt);
            statistAllPayOrder.setCountNum(countNum);
            statistAllPayOrder.setOrderLiters(orderLiters);
            statistAllPayOrder.setReceivableAmt(receivableAmt);
            statistAllPayOrder.setReceivedAmt(receivedAmt);
            statistAllPayOrder.setDiscountAmt(discountAmt);
            statisticsPayOrdersVo.add(statistAllPayOrder);
        }


//        List<StatisticsPayOrder> statisticsPayOrderList = payOrderMap.values().stream().flatMap(List::stream).collect(Collectors.toList());

        //给已经划分大区的油企赋值大区名称
        for (StatisticsPayOrder statisticsPayOrder : statisticsPayOrdersVo) {
            String district = memberManagementService.getDistrictByEnterpriseId(statisticsPayOrder.getEnterpriseId());
            if (StringUtils.isNotBlank(district)) {
                statisticsPayOrder.setDistrict(district);
            }
        }
        return statisticsPayOrdersVo;
    }

    @Override
    public StatisticsPayOrder newSelectStatisticsPayOrderSum(PayOrder payOrder) {
        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user = current.getUser();
        //判断用户等级进行赋值
        assignPayOrder(payOrder, user);
        payOrder.setStatus("1");
        StatisticsPayOrder statisticsPayOrder = payOrderMapper.newSelectStatisticsPayOrderSum(payOrder);
        StatisticsPayOrder payOrderHistorySum = payOrderHistoryMapper.newSelectStatisticsPayOrderHistorySum(payOrder);
        if (ObjectUtils.isNotEmpty(payOrderHistorySum)) {
            statisticsPayOrder.setOrderLiters(getOrderBigDecimal(statisticsPayOrder.getOrderLiters()).add(getOrderBigDecimal(payOrderHistorySum.getOrderLiters())));
            statisticsPayOrder.setReceivedAmt(getOrderBigDecimal(statisticsPayOrder.getReceivedAmt()).add(getOrderBigDecimal(payOrderHistorySum.getReceivedAmt())));
            statisticsPayOrder.setReceivableAmt(getOrderBigDecimal(statisticsPayOrder.getReceivableAmt()).add(getOrderBigDecimal(payOrderHistorySum.getReceivableAmt())));
            statisticsPayOrder.setDiscountAmt(getOrderBigDecimal(statisticsPayOrder.getDiscountAmt()).add(getOrderBigDecimal(payOrderHistorySum.getDiscountAmt())));
            statisticsPayOrder.setCountNum(statisticsPayOrder.getCountNum() + payOrderHistorySum.getCountNum());
            statisticsPayOrder.setAmt(getOrderBigDecimal(statisticsPayOrder.getAmt()).add(getOrderBigDecimal(payOrderHistorySum.getAmt())));
            return statisticsPayOrder;
        }
        return statisticsPayOrder;
    }

    /**
     * 开发的时候 特别多空值
     *
     * @param bigDecimal
     * @return
     */
    public BigDecimal getOrderBigDecimal(BigDecimal bigDecimal) {
        if (null == bigDecimal) {
            return new BigDecimal("0.00");
        }
        return bigDecimal;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult sxfRefund(PayOrder payOrder) throws Exception {
        int i = 0;
        //PayOrder payOrder=payOrderMapper.selectPayOrderById(payOrder1.getOrderId());
        // 判断originalAmt是否为空或者为null
        if (payOrder != null && payOrder.getOriginalAmt() != null) {
            // 如果originalAmt有值，则将其赋值给amt
            payOrder.setAmt(payOrder.getOriginalAmt());
        }
        if (payOrder.getPayWayId() == null) {
            throw new SQLException("支付方式为空");
        }
        PayWay payWay = payWayMapper.selectPayWayById(payOrder.getPayWayId());
//        payOrder.setStatus("3");
//        i= payOrderMapper.updatePayOrder(payOrder);
//        if(i==0){
//            throw  new CustomException("订单更新失败");
//        }

        String payType = payWay.getPayType();
//        payType="5";
        SysRespon respon = new SysRespon();
        if ("2".equals(payType)) {
            BigDecimal amt = payOrder.getAmt().multiply(BigDecimal.valueOf(100));
            Long amtvalue = amt.longValue();
            ;
            respon = saoBeiRefund(payWay.getSecretKey(), payWay.getMno(), payWay.getTerminalNo(), payOrder.getOrderNo(), amtvalue + "");
            if (!"0000".equals(respon.getResponCode())) {
                throw new CustomException(respon.getResponMessage());
            }
            payOrder.setStatus("3");
            i = payOrderMapper.updatePayOrder(payOrder);
        } else if ("1".equals(payType)) {
            //查询订单是否在随行付的支付记录中有数据 ，有则替换掉原始订单号
            if (!StringUtils.isNotBlank(payOrder.getUnitePayOrderNo())) {
                // 非多油品合并支付退款
                BigDecimal amt = payOrder.getAmt();
                String orderNo = payOrder.getOrderNo();
                if (payOrder.getPayType().equals("pos")) {
                    if (payOrder.getCreatedDate() != null) {
                        LocalDateTime createTime = LocalDateTimeUtil.parseLdt(payOrder.getCreatedDate());
                        if (createTime.isBefore(POS_ORDER_NO_CHANGE_TIME)) { // todo
                            TradePaymentRecordsDO recordsDO = tradePaymentRecordsMapper.selectOneOrderSn(payOrder.getOrderNo());
                            orderNo = recordsDO == null ? payOrder.getOrderNo() : recordsDO.getOrdNo();
                        }
                    }
                }
                respon = sendSxfRefundOrder(amt, orderNo, payWay.getMno());

//            respon= sendSxfRefund(payOrder,payWay.getMno());
                if (!"0000".equals(respon.getResponCode())) {
                    throw new CustomException(respon.getResponMessage());
                }
                payOrder.setStatus("3");
                i = payOrderMapper.updatePayOrder(payOrder);
                orderPrintService.printRefundOrder(payOrder);
            } else {
                // 多油品合并支付退款
                unitePayRefund(payOrder, payWay, (po, pw) -> {
                    try {
                        SysRespon respon1 = sendSxfRefundOrder(po.getAmt(), po.getOrderNo(), pw.getMno());
                        if (!"0000".equals(respon1.getResponCode())) {
                            throw new CustomException(respon1.getResponMessage());
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw new CustomException("退款失败");
                    }
                });
            }

        } else if ("3".equals(payType)) {
            BigDecimal amt = payOrder.getAmt().multiply(BigDecimal.valueOf(100));
            Long amtvalue = amt.longValue();
            ;
            if ("0".equals(payWay.getTlFusFlag())) {
                respon = refund(payOrder, payWay, amtvalue);
                if (!"0000".equals(respon.getResponCode())) {
                    throw new CustomException(respon.getResponMessage());
                }
            } else if ("1".equals(payWay.getTlFusFlag())) {
                respon = tLFusClassPayApply(payOrder, payWay, amtvalue);
                if (!"0000".equals(respon.getResponCode())) {
                    throw new CustomException(respon.getResponMessage());
                }
            }
            payOrder.setStatus("3");
            i = payOrderMapper.updatePayOrder(payOrder);
        } else if ("4".equals(payType)) {
            BigDecimal amt = payOrder.getAmt().multiply(BigDecimal.valueOf(100));
            Long amtvalue = amt.longValue();
            ;
            respon = JKRefund(payOrder, payWay, amtvalue);
            if (!"0000".equals(respon.getResponCode())) {
                throw new CustomException(respon.getResponMessage());
            }
            payOrder.setStatus("3");
            i = payOrderMapper.updatePayOrder(payOrder);
        } else if ("5".equals(payType)) {
            if (!StringUtils.isNotBlank(payOrder.getUnitePayOrderNo())) {
                //            respon=yunHuaRefund(payOrder, payWay);
                respon = yunHuaRefundV2(payOrder, payWay);
                if (!"0000".equals(respon.getResponCode())) {
                    throw new CustomException(respon.getResponMessage());
                }
                payOrder.setStatus("3");
                i = payOrderMapper.updatePayOrder(payOrder);
                //打印退款小票
                orderPrintService.printRefundOrder(payOrder);
//            settleInfoPushService.pushSettleInfo(payOrder);
            } else {
                unitePayRefund(payOrder, payWay, (po, pw) -> {
                    try {
                        SysRespon respon1 = yunHuaRefundV2(po, pw);
                        if (!"0000".equals(respon1.getResponCode())) {
                            throw new CustomException(respon1.getResponMessage());
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw new CustomException("退款失败");
                    }
                });
            }
        } else {
            return AjaxResult.error("支付方式的类型不存在");
        }
        // 扣减对应订单获得的积分
        subtractInteger(payOrder.getOrderNo(), payOrder.getCustomerPhone(), payOrder.getEnterpriseId());
        return AjaxResult.success(1);
    }


    private void unitePayRefund(PayOrder payOrder, PayWay payWay, BiConsumer<PayOrder, PayWay> consumer) {
        // 多油品合并支付退款
        UnitePayOrder form = new UnitePayOrder();
        form.setUniteOrderNo(payOrder.getUnitePayOrderNo());
        QueryWrapper<UnitePayOrder> qw = Wrappers.query(form);
        qw.last("limit 1");
        UnitePayOrder one = unitePayOrderService.getOne(qw);
        if (one == null) {
            throw new CustomException("合并支付订单号未找到");
        }
        if (!StringUtils.equals("1", one.getStatus())) {
            throw new CustomException("合并支付订单状态不对");
        }
        BigDecimal amt = one.getAmt();
        String orderNo = one.getUniteOrderNo();
        UnitePayOrderRel of = new UnitePayOrderRel();
        of.setUniteOrderNo(one.getUniteOrderNo());
        List<UnitePayOrderRel> orderRelList = unitePayOrderRelService.list(Wrappers.query(of));
        PayOrder payOrder1 = new PayOrder();
        payOrder1.setOrderNo(orderNo);
        payOrder1.setAmt(amt);
        payOrder1.setReceivedAmt(amt);
        payOrder1.setMerchantsNumber(one.getTransNo());
        payOrder1.setTransactionId(one.getPayNo());
        payOrder1.setPayWayId(one.getPayWayId());
        payOrder1.setStationId(one.getStationId());
        payOrder1.setActualAmt(amt);
        consumer.accept(payOrder1, payWay);
        UnitePayOrder upd = new UnitePayOrder();
        upd.setId(one.getId());
        upd.setStatus("3");
        unitePayOrderService.updateById(upd);
        payOrder.setStatus("3");
        int i = payOrderMapper.updatePayOrder(payOrder);
        orderPrintService.printRefundOrder(payOrder);
        for (UnitePayOrderRel orderRel : orderRelList) {
            if (StringUtils.equals(orderRel.getOrderNo(), payOrder.getOrderNo())) {
                continue;
            }
            PayOrder payOrder2 = payOrderMapper.selectPayOrderByOrdNo(orderRel.getOrderNo());
            if (payOrder2 == null) {
                log.info("多油品退款订单号未找到,orderNo:[{}]", orderRel.getOrderNo());
                continue;
            }
            PayOrder updateOrder = new PayOrder();
            updateOrder.setOrderId(payOrder2.getOrderId());
            updateOrder.setRefundSuccessDate(new Date());
            updateOrder.setStatus("3");
            updateOrder.setExaminDate(new Date());
            updateOrder.setExaminStatus("2");
            payOrderMapper.updatePayOrder(updateOrder);
            orderPrintService.printRefundOrder(payOrder2);
        }
    }

    private void subtractInteger(String orderNo, String mobilePhone, Long enterpriseId) {
        if (StringUtils.isBlank(orderNo) || StringUtils.isBlank(mobilePhone) || enterpriseId == null) {
            log.error("参数为空,orderNo:{},mobilePhone:{},enterpriseId:{}", orderNo, mobilePhone, enterpriseId);
            return;
        }
        CustomerPointsRecord record = new CustomerPointsRecord();
        record.setOrderNo(orderNo);
        record.setMobilePhone(mobilePhone);
        record = customerPointsRecordMapper.getOne(record);
        SysAppUserInfo appUserInfo = new SysAppUserInfo();
        appUserInfo.setMobilePhone(mobilePhone);
        appUserInfo.setStationId(enterpriseId);
        appUserInfo = appUserInfoMapper.getOne(appUserInfo);
        if (record == null || appUserInfo == null) {
            log.error("积分记录或用户未找到,orderNo:{},mobilePhone:{},enterpriseId:{}", orderNo, mobilePhone, enterpriseId);
            return;
        }
        Long userIntegral = appUserInfo.getIntegral();
        if (userIntegral == 0) {
            log.error("用户积分为0,orderNo:{},mobilePhone:{},enterpriseId:{}", orderNo, mobilePhone, enterpriseId);
            return;
        }
        Long recordIntegral = record.getIntegral();
        Long subIntegral = userIntegral < recordIntegral ? userIntegral : recordIntegral;
        SysAppUserInfo newAppUserInfo = new SysAppUserInfo();
        newAppUserInfo.setUserId(appUserInfo.getUserId());
        newAppUserInfo.setIntegral(userIntegral - subIntegral);
        appUserInfoMapper.updateAppUserInfo(newAppUserInfo);
        record.setId(null);
        record.setIntegral(subIntegral);
        record.setRecordType("-");
        record.setAction(integralTypeEnum.REFUND);
        record.setCreateTime(new Date());
        customerPointsRecordMapper.insertCustomerPointsRecord(record);
        customerPointsRecordService.wxgzhIntegralPush(record);
    }

    public SysRespon sendSxfRefund(PayOrder payOrder, String mno) throws Exception {

        SysRespon respon = new SysRespon();

        Random random = new Random();
        String result1 = "";
        for (int i = 0; i < 6; i++) {
            result1 += random.nextInt(10);
        }
        String ordNo = System.nanoTime() + result1;
        JSONObject reqData = new JSONObject();
        reqData.put("mno", mno);
        reqData.put("ordNo", ordNo);
        reqData.put("origOrderNo", payOrder.getOrderNo());
        reqData.put("amt", payOrder.getAmt());
        String req = SXFPaySign.getSXFPay(reqData);
        ///logger.debug("参数信息："+req);
        System.out.println("req:" + req);
        //此处不要改变reqData里面值的顺序用LinkedHashMap
        HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
        //组装加密串
        String signContent = RSASignature.getOrderContent(reqMap);
        System.out.println("拼接后的参数：" + signContent);
        //logger.debug("拼接后的参数："+signContent);
        //sign
        String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
        System.out.println("============签名:" + sign);
        reqMap.put("sign", sign);
        String reqStr = JSON.toJSONString(reqMap);
        System.out.println("请求参数:" + reqMap);
        System.out.println("请求参数:" + reqStr);
        //调用第三方接口地址
        String url = "https://openapi.suixingpay.com/order/refund";//生产地址
        String resultJson = HttpUtils.connectPostUrl(url, reqStr);
        System.out.println("返回信息：" + resultJson);
        //不要对reqData排序 所以用LinkedHashMap
        HashMap<String, Object> result = JSON.parseObject(resultJson, LinkedHashMap.class, Feature.OrderedField);
        if ("0000".equals(result.get("code"))) {
            //验签
            String signResult = result.get("sign").toString();
            result.remove("sign");
            String resultStr = RSASignature.getOrderContent(result);
            System.out.println("resultStr: " + resultStr);
            //sign
            String resultSign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
            System.out.println("resultSign: " + resultSign);
            //组装加密串
            if (RSASignature.doCheck(resultStr, signResult, SXFPaySign.sxfPublic)) {
                System.out.println("===================验签成功==============");
                //
                if (result.containsKey("respData")) {
                    HashMap<String, Object> result2 = JSON.parseObject(result.get("respData") + "", LinkedHashMap.class, Feature.OrderedField);
                    if ("0000".equals(result2.get("bizCode"))) {
                        respon.setResponCode("0000");
                        respon.setResponMessage(result2.get("bizMsg") + "");
                        return respon;
                    } else {
                        respon.setResponCode(result2.get("bizCode") + "");
                        respon.setResponMessage(result2.get("bizMsg") + "");
                    }
                    //判断 bizCode bizCode =="0000" 则业务成功
                } else {
                    respon.setResponCode("0004");
                    respon.setResponMessage(result.get("msg") + "");
                }
            } else {
                respon.setResponCode("0002");
                respon.setResponMessage("RSA验证失败");
            }
        } else {
            respon.setResponMessage(result.get("msg") + "");
            respon.setResponCode(result.get("code") + "");
        }
        return respon;
    }


    private SysRespon saoBeiRefund(String token, String mno, String termialId, String oldOrderNo, String amt) throws Exception {
        //创建client
        DefaultSaobeiApiClient<SaobeiTradeRefundRequest, SaobeiTradeRefundResponse> client = new DefaultSaobeiApiClient<>(token);//令牌的token
        //创建requst
        SaobeiTradeRefundRequest requst = new SaobeiTradeRefundRequest();
        Random random = new Random();
        String result1 = "";
        for (int i = 0; i < 6; i++) {
            result1 += random.nextInt(10);
        }
        String ordNo = System.nanoTime() + result1;
        requst.setPay_ver("110");//
        requst.setPay_type("000");
        requst.setService_id("030");
        requst.setMerchant_no(mno);//商户号
        requst.setTerminal_id(termialId);//终端号
        requst.setTerminal_trace(ordNo);//退款时生成的终端流水号
        requst.setTerminal_time(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()));//退款时间
        requst.setOut_trade_no(oldOrderNo);//订单号
        requst.setRefund_fee(amt);//退款金额，单位是分
        /**/
        //发送请求
        System.out.println("请求报文:" + JSON.toJSONString(requst));
        SaobeiTradeRefundResponse response = client.execute(requst);
        System.out.println("返回报文:" + JSON.toJSONString(response));

        SysRespon sysRespon = new SysRespon();
        HashMap<String, Object> result = JSON.parseObject(JSON.toJSONString(response), LinkedHashMap.class, Feature.OrderedField);
        if ("01".equals(result.get("return_code"))) {
            if ("退款成功".equals(result.get("return_msg"))) {
                sysRespon.setResponCode("0000");
                sysRespon.setResponMessage("退款成功");
            } else {
                sysRespon.setResponCode("0001");
                sysRespon.setResponMessage(result.get("return_msg") + "");
            }
        } else {
            sysRespon.setResponCode("0002");
            sysRespon.setResponMessage("网络请求失败");

        }
        return sysRespon;

    }


    //生产环境


    private static <T> String post(String service, T body, String appId, String appKey) throws IOException {
        Request<T> request = new Request<>();
        request.setAppId(appId);
        request.setCharset("utf-8");
        request.setSignType("MD5");
        request.setVersion("11");
        request.setTimestamp(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
        request.setService(service);
        request.setBizContent(body);
        request.sign(appKey);
        String result = HttpUtils.post("https://merchant.allinpaygd.com/gateway", request.toMap());
        request.verify(result, appKey);
        return result;
    }

    /***
     * 通联支付： 业务使用实时班结，与分账支付时调用；
     * @param
     * @return
     * @throws IOException
     */
    public SysRespon tLFusClassPayApply(PayOrder payOrder, PayWay payWay, Long amtvalue) throws IOException {
        SysRespon sysRespon = new SysRespon();

        Random random = new Random();
        String result1 = "";
        for (int i = 0; i < 6; i++) {
            result1 += random.nextInt(10);
        }
        String ordNo = System.nanoTime() + result1;
        HashMap resultInfo = new HashMap();
        Tlparam payApply = new Tlparam();
        payApply.setSysId(payWay.getTlSysId());           //系统ID
        payApply.setOldBizOrderNo(payOrder.getOrderNo());
        //payApply.setOldBizOrderNo("1645517510567428967");
        payApply.setBizOrderNo(ordNo); //订单号
        payApply.setAmount(amtvalue);         //金额

        List<ConsumeType> consumeTypes = new ArrayList<>();
        ConsumeType consumeType = new ConsumeType();
        consumeType.setType("C0001");               //业务类型 C0001 加油； C0002：便利店； C0003：洗车；
        consumeType.setAmount(amtvalue);

        consumeTypes.add(consumeType);
        payApply.setConsumeTypes(consumeTypes);


        payApply.setShiftsTime(payOrder.getTlShiftsTime());     //班次时间
        payApply.setShiftsMask(payOrder.getTlShiftsMask());     //班次标识


        /*返回参数
        {
        "msg":"SUCCESS",
        "payInterfaceTrxCode":"",
        "finishTime":"",
        "code":"SUCCESS",
        "orderNo":"P20220118000000012424451",
        "payStatusMsg":"进行中",
        "sysId":"1480833167961694210",
        "bizCode":"0000",
        "sign":"56ad0f322a4ab753452d22753522709c",
        "remark":"这是备注",
        "shiftsTime":"20220118",
        "shiftsMask":"2",
        "bizMsg":"处理成功",
        "payInfo":"{\"appId\":\"wxb46701bd193ee573\",
                    \"timeStamp\":\"1642494427\",
                    \"nonceStr\":\"1924ebadd7314805ac762e7c7eeaa530\",
                    \"package\":\"prepay_id=wx18162707708597421cf8564bcf054c0000\",
                    \"signType\":\"RSA\",
                    \"paySign\":\"M5IUB1NrFmcn83vaG8ekvWkmVLFon2ziisM0HXKnT7O/aaeGSAlbYI8VsnUhUgEEl3duncfIqYaA+8m454xjuA0pGHitVPeRNBvoIKR+ojiCJhT2MgfZSgE1x2Js518ZpfLT2Fbthn37Tu8ow48MzpNvy4zytkiof0IzX2bNyi4JTnoZW7aLyW963m2pL+KzLS7ZXGAXU/k8utyTwXZGMGRnNkguE0Jf2ra7GxVVAT4vxmh0GfW3e/Vqq8iL6xIqdMn+bPo6vteWgfjDcs3EKpmlbsEcv7lJN0gClPou3+prEBEf22M2dfKoAz/JgY4THPEQZX2QFxtnc8pl1gX7Lg==\"
                    }",
        "payStatus":"2000",
        "bizOrderNo":"1642494424396"
        }
        * */
        String post = post("oil.pay.refund", payApply, payWay.getTlAppId(), payWay.getTlAppKey());

        JSONObject jsonObject = JSON.parseObject(post);
        if ("0000".equals(jsonObject.get("bizCode").toString())) {
            sysRespon.setResponCode("0000");
            sysRespon.setResponMessage("退款成功");
        } else {
            sysRespon.setResponCode(jsonObject.get("bizCode").toString());
            sysRespon.setResponMessage(jsonObject.get("bizMsg").toString());
        }
        return sysRespon;
    }

    //通联收银宝支付的订单进行退款
    public SysRespon refund(PayOrder payOrder, PayWay payWay, Long amt) throws Exception {
        SysRespon sysRespon = new SysRespon();
        Random random = new Random();
        String result1 = "";
        for (int i = 0; i < 6; i++) {
            result1 += random.nextInt(10);
        }
        String ordNo = System.nanoTime() + result1;
        HttpConnectionUtil http = new HttpConnectionUtil("https://vsp.allinpay.com/apiweb/unitorder" + "/refund");
        http.init();
        TreeMap<String, String> params = new TreeMap<String, String>();

        params.put("cusid", payWay.getMno());
        params.put("appid", payWay.getAllinpayAppId());
        params.put("version", "11");
        params.put("trxamt", amt + "");
        params.put("reqsn", ordNo);
        params.put("oldreqsn", payOrder.getOrderNo());

        params.put("randomstr", SybUtil.getValidatecode(8));
        params.put("signtype", "RSA");
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (entry.getValue() != null && entry.getValue().length() > 0) {
                sb.append(entry.getKey()).append("=").append(entry.getValue())
                        .append("&");
            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        params.put("sign", SybUtil.unionSign(params, payWay.getAllinpayRSAKey(), "RSA"));
        byte[] bys = http.postParams(params, true);
        String result = new String(bys, "UTF-8");
        Map<String, String> map = handleResult(result);
        if ("0000".equals(map.get("trxstatus"))) {
            Map payInfoMap = JSON.parseObject(map.get("payinfo"), Map.class);
            sysRespon.setResponCode("0000");
            sysRespon.setResponMessage("退款成功");
        } else {
            sysRespon.setResponCode(map.get("trxstatus"));
            sysRespon.setResponMessage(map.get("errmsg"));
        }
        return sysRespon;
    }

    //通联返回值信息进行解析
    public static Map<String, String> handleResult(String result) throws Exception {
        System.out.println("ret:" + result);
        Map map = SybUtil.json2Obj(result, Map.class);
        if (map == null) {
            throw new Exception("返回数据错误");
        }
        if ("SUCCESS".equals(map.get("retcode"))) {
            TreeMap tmap = new TreeMap();
            tmap.putAll(map);
            String appkey = "";
            if (SybConstants.SIGN_TYPE.equals("RSA"))
                appkey = SybConstants.SYB_RSATLPUBKEY;
            else if (SybConstants.SIGN_TYPE.equals("SM2"))
                appkey = SybConstants.SYB_SM2TLPUBKEY;
            else
                appkey = SybConstants.SYB_MD5_APPKEY;
            if (SybUtil.validSign(tmap, appkey, SybConstants.SIGN_TYPE)) {
                System.out.println("签名成功");
                return map;
            } else {
                throw new Exception("验证签名失败");
            }

//            TreeMap tmap = new TreeMap();
//            tmap.putAll(map);
//            String appkey = "";
//            if(tlPayParam.getSIGN_TYPE().equals("RSA"))
//                appkey = tlPayParam.getSYB_RSACUSPRIKEY();
//            else if(tlPayParam.getSIGN_TYPE().equals("SM2"))
//                appkey = tlPayParam.getSYB_SM2PPRIVATEKEY();
//            else
//                appkey = tlPayParam.getSYB_MD5_APPKEY();
//            if(SybUtil.validSign(tmap, appkey, tlPayParam.getSIGN_TYPE())){
//                System.out.println("签名成功");
//                return map;
//            }else{
//                throw new Exception("验证签名失败");
//            }

        } else {
            throw new Exception(map.get("retmsg").toString());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int chengePayOrder() throws Exception {
        int i = 0;
        i = payOrderMapper.chengePayOrderToHistory();
        if (i < 0) {
            throw new Exception("转移失败");
        }
        return i;
    }

    //金控退款
    public SysRespon JKRefund(PayOrder payOrder, PayWay payWay, Long amt) throws Exception {
        SysRespon sysRespon = new SysRespon();
        Random random = new Random();
        String result1 = "";
        for (int i = 0; i < 6; i++) {
            result1 += random.nextInt(10);
        }
        String ordNo = System.nanoTime() + result1;
        GatewayRequest param = new GatewayRequest();
        param.setTransCode("refundOrder");
        param.setMerchantNo(payWay.getMno()); //商户编号
        param.setMerOrderNo(ordNo); // 生成的商户订单号

        param.setMerSubmitTime(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())); //提交时间
        param.setSignType("3"); // cfca-RSA证书签名
        param.setTransVersion("1.0");
        // 组装 --参考接口文档相关参数
        JSONObject object = new JSONObject();

        object.put("orderNo", payOrder.getMerchantsNumber()); //原金控交易订单号
        object.put("refundAmount", amt); //交易金额--单位分
        object.put("curType", "CNY"); //交易币种--CNY(人民币)
        object.put("refundTime", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())); //微信用户标识
        object.put("refundDesc", "申请退款"); //退款原因，必填项

        System.out.println("请求参数为=" + object);
        String msgcip = Base64Util.encode(object.toString());
        param.setMsgCipherText(msgcip);
        System.out.println(param.toString());
        try {
            Map<String, Object> sign = Tools.objectToMap(param);
            // 组装签名值
            String content = ParaUtils.createLinkStringObj(ParaUtils.removeMap(sign));
            // 签名
            byte[] msg = CfcaCertUtil.signMessage(content, private_pfxPath, "zhyj2022"); //商户自己的私钥签名
            String signValue = new String(msg);
            param.setSignValue(signValue);
            // 发送请求信息
            String rspMsg = HttpClientUtil.post("https://saas.mfe88.com/gateway-scan-pay/api/scanRefund", JSONObject.toJSONString(param), 3000, "application/json", "utf-8");
            System.out.println("返回结果=" + rspMsg);
            GatewayResponse gatewayResponse = new ObjectMapper().readValue(rspMsg, GatewayResponse.class);
            if ("0000".equals(gatewayResponse.getRespCode())) { // 受理成功
                //验签处理
                Map<String, Object> verifyMap = Tools.objectToMap(gatewayResponse);
                String verifyContent = ParaUtils.createLinkStringObj(ParaUtils.removeMap(verifyMap));
                String signvalue = gatewayResponse.getSignValue();
                // 验签
                boolean checkverify = CfcaCertUtil.verifyValue(verifyContent, signvalue, public_certPath); //现代支付公钥
                if (checkverify) { //验签成功
                    String orderInfo = Base64Util.decodeString(gatewayResponse.getOrderInfo());
                    JSONObject orderObj = JSONObject.parseObject(orderInfo);
                    System.out.println(orderInfo);
                    if ("0000".equals(orderObj.get("resultCode") + "") && "01".equals(orderObj.get("orderStatus"))) {
                        sysRespon.setResponCode("0000");
                        sysRespon.setResponMessage("退款申请成功");
                    } else {
                        sysRespon.setResponCode(orderObj.get("resultCode") + "");
                        sysRespon.setResponMessage(orderObj.get("resultDesc") + "");
                        throw new Exception(orderObj.get("resultDesc") + "");
                    }


                    // 根据返回结果--商户后续处理。TODO
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sysRespon;

    }

    //云华退款
    public SysRespon yunHuaRefund(PayOrder payOrder, PayWay payWay) throws Exception {
        SysRespon sysRespon = new SysRespon();
        Random random = new Random();
        String result1 = "";
        for (int i = 0; i < 6; i++) {
            result1 += random.nextInt(10);
        }
        String nowdate = new SimpleDateFormat("yyyMMddHHmm").format(new Date());
        String nowdate1 = new SimpleDateFormat("yyyMMdd").format(new Date());
        String ordNo = System.nanoTime() + result1;
        YunHuaRefundParam yunHuaRefundParam = YunHuaRefundParam.builder()
                //.partnerCode(payWay.getTerminalNo())
                .partnerCode(payWay.getTerminalNo())
                .posDate(nowdate)
                .posOrderNo(ordNo)
                //.refundAmt(payOrder.getAmt())
                .refundAmt(payOrder.getAmt())
                .refundDate(nowdate1)
                .refundDesc("申请退款")
                .signType("SHA256")
                // .srcPosOrderNo(payOrder.getOrderNo())
                .srcPosOrderNo(payOrder.getOrderNo())
                .build();
        JSONObject beforeSign = JSONObject.parseObject(yunHuaRefundParam.toRefundAmt());
        String sign = SignService.getSign(beforeSign, payWay.getSecretKey());
        yunHuaRefundParam.setSign(sign);
        String mmmm = yunHuaRefundParam.toRefundAmt();
        System.out.println(mmmm);
        String res = com.qujia.station.utils.HttpUtils.connectPostUrl("http://123.60.22.157:31120/marketing/pay/refund", mmmm);
//        String res=  com.qujia.station.utils.HttpUtils.connectPostUrl("https://yh.xailife.com/marketing-dev01/pay/refund", mmmm);


        System.out.println(res);
        JSONObject result = JSONObject.parseObject(res);
        if (!"0000".equals(result.get("code") + "")) {
            sysRespon.setResponCode("0001");
            sysRespon.setResponMessage(result.get("message") + "");

        }
        JSONObject data = JSONObject.parseObject(result.get("data") + "");
        if (!"T".equals(data.getString("tbRefundStatus"))) {
            sysRespon.setResponCode("0001");
            sysRespon.setResponMessage(result.get("message") + "");
        } else {
            sysRespon.setResponCode("0000");
            sysRespon.setResponMessage(result.get("message") + "");
        }

        return sysRespon;

    }


    @Override
    public SysRespon yunHuaRefundV2(PayOrder payOrder, PayWay payWay) throws Exception {
        Random random = new Random();
        String result1 = "";
        for (int i = 0; i < 6; i++) {
            result1 += random.nextInt(10);
        }
        String refundOrderNo = System.nanoTime() + result1;
        return yunHuaRefundV2(refundOrderNo, payOrder, payWay);
    }

    //云华退款
    @Override
    public SysRespon yunHuaRefundV2(String refundOrderNo, PayOrder payOrder, PayWay payWay) throws Exception {
        SysRespon sysRespon = new SysRespon();
//        Random random = new Random();
//        String result1 = "";
//        for (int i = 0; i < 6; i++) {
//            result1 += random.nextInt(10);
//        }
        String nowdate = new SimpleDateFormat("yyyMMddHHmm").format(new Date());
        String nowdate1 = new SimpleDateFormat("yyyMMdd").format(new Date());
        //String ordNo = System.nanoTime() + result1;
        YunHuaRefundParam yunHuaRefundParam = YunHuaRefundParam.builder()
                //.partnerCode(payWay.getTerminalNo())
                .partnerCode(payWay.getMno())
                .posDate(nowdate)
                .posOrderNo(refundOrderNo)
                //.refundAmt(payOrder.getAmt())
                .refundAmt(payOrder.getReceivedAmt())
                .refundDate(nowdate1)
                .refundDesc("申请退款")
                .signType("SHA256")
                // .srcPosOrderNo(payOrder.getOrderNo())
                .srcPosOrderNo(payOrder.getOrderNo())
                .memberNumber(payOrder.getMerchantsNumber())
                .payNo(payOrder.getTransactionId())
                .build();
        JSONObject beforeSign = JSONObject.parseObject(yunHuaRefundParam.toRefundAmtV2());
        String sign = VerifySignUtil.getSign(beforeSign, payWay.getSecretKey());
        yunHuaRefundParam.setSign(sign);
        String mmmm = yunHuaRefundParam.toRefundAmtSingV2();
        System.out.println(mmmm);
        String res = com.qujia.station.utils.HttpUtils.connectPostUrl(yunHuaRefundUrl, mmmm);
//        String res=  com.qujia.station.utils.HttpUtils.connectPostUrl("https://yh.xailife.com/marketing-dev01/pay/refund", mmmm);


        System.out.println(res);
        JSONObject result = JSONObject.parseObject(res);


        if (!"0000".equals(result.get("code"))) {
            sysRespon.setResponCode("0001");
            sysRespon.setResponMessage(result.get("message") + "");

        }
        JSONObject data = result.getJSONObject("data");
        if ("3".equals(data.getString("status")) || "2".equals(data.getString("status"))) {
            sysRespon.setResponCode("0000");
            sysRespon.setResponMessage("退款申请受理成功");
            settleInfoPushService.pushSettleInfo(payOrder, data);
        } else {
            sysRespon.setResponCode("0001");
            sysRespon.setResponMessage(data.get("message") + "");
        }
        sysRespon.setData(data);
        return sysRespon;

    }

    @Override
    public String selectOrderStatus(PayOrder payOrder) {
        PayOrder payOrder1 = payOrderMapper.selectPayOrderById(payOrder.getOrderId());
        PayWay payWay = payWayMapper.selectPayWayById(payOrder1.getPayWayId());
        YunHuaRefundParam yunHuaRefundParam = YunHuaRefundParam.builder()
                //.partnerCode(payWay.getTerminalNo())
                .partnerCode(payWay.getMno())
                .posOrderNo(payOrder1.getOrderNo())
                .build();
        JSONObject beforeSign = JSONObject.parseObject(yunHuaRefundParam.toSelectOrder());
        String sign = VerifySignUtil.getSign(beforeSign, payWay.getSecretKey());
        yunHuaRefundParam.setSign(sign);
        String mmmm = yunHuaRefundParam.toSelectOrderSign();
        System.out.println(mmmm);
        String res = null;
        try {
            res = com.qujia.station.utils.HttpUtils.connectPostUrl("https://paydev01.xailife.com/front/upi/refund", mmmm);
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        String res=  com.qujia.station.utils.HttpUtils.connectPostUrl("https://yh.xailife.com/marketing-dev01/pay/refund", mmmm);


        System.out.println(res);
        JSONObject result = JSONObject.parseObject(res);
        if (!"0000".equals(result.get("code") + "")) {

        }
        JSONObject data = JSONObject.parseObject(result.get("data") + "");
        if (!"3".equals(data.getString("status"))) {
            return "订单未退款";
        } else {
            PayOrder payOrder2 = new PayOrder();
            payOrder2.setStatus("3");
            payOrder2.setOrderId(payOrder.getOrderId());
            payOrderMapper.updatePayOrder(payOrder);
            return "订单已退款";

        }

    }

    /**
     * 查询总数
     *
     * @return
     */
    @Override
    public int getStatusCount(PayOrder payOrder) {
        int count = payOrderMapper.countByStatus(payOrder);
        return count;
    }

    /**
     * 汇总订单统计信息
     *
     * @param payOrder
     * @return
     */
    @Override
    public PayOrder selectSumPayOrder(PayOrder payOrder) {
        return payOrderMapper.selectSumPayOrder(payOrder);
    }

    @Override
    public SysRespon sendSxfRefundOrder(BigDecimal amt, String origOrderNo, String mno) throws Exception {
        Random random = new Random();
        String result1 = "";
        for (int i = 0; i < 6; i++) {
            result1 += random.nextInt(10);
        }
        String ordNo = System.nanoTime() + result1;
        return sendSxfRefundOrder(amt, ordNo, origOrderNo, mno);
    }

    @Override
    public SysRespon sendSxfRefundOrder(BigDecimal amt, String orderNo, String origOrderNo, String mno) throws Exception {

        SysRespon respon = new SysRespon();

        JSONObject reqData = new JSONObject();
        reqData.put("mno", mno);
        reqData.put("ordNo", orderNo);
        reqData.put("origOrderNo", origOrderNo);
        reqData.put("amt", amt);
        String req = SXFPaySign.getSXFPay(reqData);
        ///logger.debug("参数信息："+req);
        System.out.println("req:" + req);
        //此处不要改变reqData里面值的顺序用LinkedHashMap
        HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
        //组装加密串
        String signContent = RSASignature.getOrderContent(reqMap);
        System.out.println("拼接后的参数：" + signContent);
        //logger.debug("拼接后的参数："+signContent);
        //sign
        String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
        System.out.println("============签名:" + sign);
        reqMap.put("sign", sign);
        String reqStr = JSON.toJSONString(reqMap);
        System.out.println("请求参数:" + reqMap);
        System.out.println("请求参数:" + reqStr);
        //调用第三方接口地址
        String url = "https://openapi.suixingpay.com/order/refund";//生产地址
        String resultJson = HttpUtils.connectPostUrl(url, reqStr);
        System.out.println("返回信息：" + resultJson);
        //不要对reqData排序 所以用LinkedHashMap
        HashMap<String, Object> result = JSON.parseObject(resultJson, LinkedHashMap.class, Feature.OrderedField);
        if ("0000".equals(result.get("code"))) {
            //验签
            String signResult = result.get("sign").toString();
            result.remove("sign");
            String resultStr = RSASignature.getOrderContent(result);
            System.out.println("resultStr: " + resultStr);
            //sign
            String resultSign = RSASignature.encryptBASE64(RSASignature.sign(signContent, SXFPaySign.privateKey));
            System.out.println("resultSign: " + resultSign);
            //组装加密串
            if (RSASignature.doCheck(resultStr, signResult, SXFPaySign.sxfPublic)) {
                System.out.println("===================验签成功==============");
                //
                if (result.containsKey("respData")) {
                    HashMap<String, Object> result2 = JSON.parseObject(result.get("respData") + "", LinkedHashMap.class, Feature.OrderedField);
                    if ("0000".equals(result2.get("bizCode"))) {
                        respon.setResponCode("0000");
                        respon.setResponMessage(result2.get("bizMsg") + "");
                        return respon;
                    } else {
                        respon.setResponCode(result2.get("bizCode") + "");
                        respon.setResponMessage(result2.get("bizMsg") + "");
                    }
                    respon.setData(result2);
                    //判断 bizCode bizCode =="0000" 则业务成功
                } else {
                    respon.setResponCode("0004");
                    respon.setResponMessage(result.get("msg") + "");
                }
            } else {
                respon.setResponCode("0002");
                respon.setResponMessage("RSA验证失败");
            }
        } else {
            respon.setResponMessage(result.get("msg") + "");
            respon.setResponCode(result.get("code") + "");
        }
        return respon;
    }

    public PayOrder assignPayOrder(PayOrder payOrder, SysUser user) {
        List<String> list = new ArrayList<>();
        if (UserConstants.LEVEL_ONE.equals(user.getUserLevel()) || StringUtils.isBlank(user.getUserLevel())) {
            if (StringUtils.isNotBlank(payOrder.getDistrictIds())) {

                List<Integer> districtIds = Arrays.stream(payOrder.getDistrictIds().split(",")).map(Integer::parseInt).collect(Collectors.toList());

                for (Integer district : districtIds) {

                    String districtName = PermissionsUtil.getDistrict(district);

                    log.info("输入的地区,{}", payOrder.getDistrictList());
                    List<Long> enterpriseByDistrict = teamManagementService.getEnterpriseByDistrict(districtName);
                    log.info("获得该地区的所有油企id：{}", enterpriseByDistrict);
                    List<String> enterpriseIds = enterpriseByDistrict.stream().map(x -> x + "").collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(enterpriseIds)) {
                        payOrder.setEnterpriseIdList(enterpriseIds);
                    } else {
                        enterpriseIds.add("0");
                        payOrder.setEnterpriseIdList(enterpriseIds);
                    }
                }
            }
        }
        if (UserConstants.LEVEL_TWO.equals(user.getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(user.getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);

            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if (UserConstants.LEVEL_THREE.equals(user.getUserLevel())) {

            payOrder.setStationId(user.getStationId());

        }

        if (UserConstants.LEVEL_FIVE.equals(user.getUserLevel())) {
            if (CollectionUtils.isEmpty(payOrder.getStationIdList()) && CollectionUtil.isEmpty(payOrder.getEnterpriseIdList())) {

                log.info("输入的负责人id：{}", user.getUserId());
                List<Long> managerEnterpriseId = teamManagementService.getManagerEnterpriseId(user.getUserId());
                log.info("该负责人id:{} , 所管理的油企id：{}", user.getUserId(), managerEnterpriseId);

                List<String> collect = managerEnterpriseId.stream().map(x -> x + "").collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(collect)) {
                    payOrder.setEnterpriseIdList(collect);
                } else {
                    collect.add("0");
                    payOrder.setEnterpriseIdList(collect);
                }

            }
        }
        if (UserConstants.LEVEL_SIX.equals(user.getUserLevel())) {
            if (CollectionUtils.isEmpty(payOrder.getStationIdList()) && CollectionUtil.isEmpty(payOrder.getEnterpriseIdList())) {

                log.info("输入的业务员id：{}", user.getUserId());
                List<Long> managerEnterpriseId = memberManagementService.getMemberEnterpriseId(user.getUserId());
                log.info("该业务员id:{} , 所管理的油企id：{}", user.getUserId(), managerEnterpriseId);

                List<String> collect = managerEnterpriseId.stream().map(x -> x + "").collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(collect)) {
                    payOrder.setEnterpriseIdList(collect);
                } else {
                    collect.add("0");
                    payOrder.setEnterpriseIdList(collect);
                }
            }
        }
        return payOrder;
    }


    @Override
    public List<PayOrder> selectPayOrderAndWithdrawalAmountList(PayOrder payOrder) {
        List<PayOrder> payOrders = payOrderMapper.selectPayOrderList(payOrder);
        // 查询支付方式
        OrderPayType orderPayType = new OrderPayType();
        orderPayType.setStationId(payOrder.getStationId());
        orderPayType.setStationIdList(payOrder.getStationIdList());
        List<OrderPayType> orderPayTypeList = orderPayTypeMapper.selectOrderPayType(orderPayType);
        for (PayOrder order : payOrders) {
            if (!StringUtils.equalsAny(order.getStatus(), "0", "4") && StringUtils.equalsAny(order.getPayType(), "wx", "zfb", "pos")) {
                order.setWithdrawalAmount(MathUtil.subtract(order.getAmt(), order.getCommission()));
            } else {
                order.setWithdrawalAmount(BigDecimal.ZERO);
            }
            setPayTypeName(order, orderPayTypeList);
        }
        return payOrders;
    }


    @Override
    public List<PayOrderExport> selectPayOrderAndWithdrawalAmountExportList(PayOrder payOrder) {
        List<PayOrderExport> payOrders = payOrderMapper.selectPayOrderExportList(payOrder);

        return payOrders;
    }

    // 匹配支付方式
    private void setPayTypeName(PayOrder payOrder, List<OrderPayType> orderPayTypeList) {
        String payTypeName = PayTypeNameEnum.getPayTypeName(payOrder.getPayType());
        if (StringUtils.isNotBlank(payTypeName)) {
            payOrder.setPayTypeName(payTypeName);
        }

        for (OrderPayType orderPayType : orderPayTypeList) {
            if (orderPayType.getPayType().equals(payOrder.getPayType())) {
                payOrder.setPayTypeName(orderPayType.getPayTypeName());
            }
        }
    }

    @Override
    public BigDecimal reductionActivitiesAmountCalculation(ReduActiVO reduActiVO) {
        //计算当前是周几以及几号，查询时间是否符合
        BigDecimal finalDeductionAmount = BigDecimal.ZERO;//最后可以被扣除的金额
        log.info("pos机开始进行立减，计算金额");
        Calendar calendar = Calendar.getInstance();
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        int month = calendar.get(Calendar.DAY_OF_MONTH);
        if (week == 1) {
            week = 7;
        } else {
            week--;
        }
        List<ReductionActivitiesAmtVO> acticity = payOrderMapper.selectReductionActivityStationId(reduActiVO);
        //当活动有且只有一个时，只需要查看是否适用于当前时间段
        for (ReductionActivitiesAmtVO amoutv0 : acticity) {

            //判断实付金额是否超过上限门槛
            if (amoutv0.getAmtUpperLimit() != null && amoutv0.getAmtUpperLimit().compareTo(reduActiVO.getAmt()) == -1) {
                continue;
            }
            LocalDateTime modifyTime = LocalDateTime.ofInstant(amoutv0.getModifyTime().toInstant(), ZoneId.systemDefault());
            if (modifyTime.isBefore(OLD_ACTIVITY_CREATE_TIME)) {
                //老活动逻辑
                //查看是否适用当前时间 生效时间段 all：全部时间段  week：按周选择 month：按月选择
                if (amoutv0.getTimeMode().equals("week") && amoutv0.getDays().contains(String.valueOf(week))) {
                    finalDeductionAmount = sumCountActivityMethods(amoutv0, finalDeductionAmount, reduActiVO);
                } else if (amoutv0.getTimeMode().equals("month") && amoutv0.getDays().contains(String.valueOf(month))) {
                    finalDeductionAmount = sumCountActivityMethods(amoutv0, finalDeductionAmount, reduActiVO);
                } else if (amoutv0.getTimeMode().equals("all")) {
                    //不是按周 按月，就一定是全部时间段生效
                    finalDeductionAmount = sumCountActivityMethods(amoutv0, finalDeductionAmount, reduActiVO);
                }
            } else {
                //新活动逻辑
                if ("all".equals(amoutv0.getTimeMode())) {
                    //全部时间
                    finalDeductionAmount = sumCountActivityMethods(amoutv0, finalDeductionAmount, reduActiVO);
                } else {
                    String days = amoutv0.getDays();
                    String weeks = amoutv0.getWeeks();
                    if (StringUtils.contains(days, String.valueOf(month)) || StringUtils.contains(weeks, String.valueOf(week))) {
                        finalDeductionAmount = sumCountActivityMethods(amoutv0, finalDeductionAmount, reduActiVO);
                    }
                }
            }

        }
        log.info("pos机进行立减，计算金额结束");
        return finalDeductionAmount;
    }

    @Override
    @Transactional
    public int dzkRefund(PayOrder payOrder) {
        //如果有赠送金额，退款后扣除电子卡的赠送金额，如果赠送金额不够扣，扣除账户余额
        String orderNo = payOrder.getOrderNo();
        PresentAmountRecord query = new PresentAmountRecord();
        query.setOrderNo(orderNo);
        query.setBusinessName(PresentAmountRecord.businessName_payOrder);
        query.setPurpose(PresentAmountRecord.purpose_add);
        List<PresentAmountRecord> presentAmountGainRecords = presentAmountRecordMapper.query(query);
        query.setPurpose(PresentAmountRecord.purpose_subtract);
        List<PresentAmountRecord> presentAmountUseRecords = presentAmountRecordMapper.query(query);
        CustomerCardUseRecord customerCardUseRecord = customerCardUseRecordMapper.selectCustomerCardUseRecordByOrderNo(orderNo);

        String cardType = customerCardUseRecord.getCardOilsType();
        if (StringUtils.isNotEmpty(cardType)) {
            CustomerElectronicCard customerElectronicCard = customerElectronicCardService.getCustomerElectronicCard(payOrder.getCustomerPhone(), cardType, payOrder.getStationId(), payOrder.getEnterpriseId());
            if (customerElectronicCard != null) {

                //回退充值立减活动储值
                if (payOrder.getRechargeDiscountAmt() != null && payOrder.getRechargeDiscountAmt().compareTo(BigDecimal.ZERO) > 0) {
                    ReductionActivityBalanceRecord recordQuery = new ReductionActivityBalanceRecord();
                    recordQuery.setCardOilsType(cardType);
                    recordQuery.setMobilePhone(customerCardUseRecord.getMobilePhone());

                    Enterprise enterprise = enterpriseMapper.selectEnterpriseById(payOrder.getEnterpriseId());
                    if (StringUtils.equals("1", enterprise.getCardUseRangeFlag())) {
                        recordQuery.setEnterpriseId(payOrder.getEnterpriseId());
                    } else {
                        recordQuery.setStationId(payOrder.getStationId());
                    }
                    List<ReductionActivityBalanceRecord> balanceRecords = reductionActivityBalanceRecordMapper.query(recordQuery);
                    if (balanceRecords.size() > 0) {
                        ReductionActivityBalanceRecord reductionActivityBalanceRecord = balanceRecords.get(0);
                        BigDecimal balance = reductionActivityBalanceRecord.getBalance();
                        balance = balance.add(payOrder.getAmt()).setScale(2, RoundingMode.HALF_UP);
                        if (balance.compareTo(BigDecimal.ZERO) < 0) {
                            balance = BigDecimal.ZERO;
                        }
                        reductionActivityBalanceRecord.setBalance(balance);
                        reductionActivityBalanceRecordMapper.update(reductionActivityBalanceRecord);
                    }
                }

                if (presentAmountUseRecords.size() > 0) {
                    PresentAmountRecord presentAmountRecord = presentAmountUseRecords.get(0);
                    BigDecimal amt = customerElectronicCard.getAmt().add(payOrder.getAmt().subtract(presentAmountRecord.getPresentAmount())).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (amt.compareTo(BigDecimal.ZERO) < 0) {
                        amt = BigDecimal.ZERO;
                    }
                    customerElectronicCard.setAmt(amt);

                    customerElectronicCard = dzkRefundUsePresentAmount(customerElectronicCard, presentAmountRecord);
                } else {
                    customerElectronicCard.setAmt(customerElectronicCard.getAmt().add(payOrder.getAmt()).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                // 退还返现金额
                if (customerElectronicCard.getReturnCashAmt().compareTo(BigDecimal.ZERO) > 0){
                    if (payOrder.getGiftReturnCash().compareTo(customerElectronicCard.getReturnCashAmt()) >= 0){
                        customerElectronicCard.setReturnCashAmt(BigDecimal.ZERO);
                    } else {
                        customerElectronicCard.setReturnCashAmt(customerElectronicCard.getReturnCashAmt().subtract(payOrder.getGiftReturnCash()));
                    }
                }
                if (presentAmountGainRecords.size() > 0) {
                    PresentAmountRecord presentAmountRecord = presentAmountGainRecords.get(0);
                    customerElectronicCard = dzkRefundGainPresentAmount(customerElectronicCard, payOrder, presentAmountRecord);

                    if (presentAmountRecord.getPresentAmount().compareTo(BigDecimal.ZERO) > 0) {
                        CustomerCardUseRecord record = new CustomerCardUseRecord();
                        record = JSON.parseObject(JSON.toJSONString(customerCardUseRecord), CustomerCardUseRecord.class);
                        record.setOrderNo(orderNo + "3");
                        record.setPresentAmt(presentAmountRecord.getPresentAmount());
                        record.setStatus("1");
                        record.setBalance(customerElectronicCard.getAmt().add(customerElectronicCard.getPresentAmt()));
                        record.setStationId(payOrder.getStationId().intValue());
                        record.setId(null);
                        record.setUsageType("-");
                        record.setPayType(CustomerCardUseRecord.PAY_TYPE_CONSUME_PRESENT_REFUND);
                        record.setAmt(null);
                        customerCardUseRecordMapper.insertCustomerCardUseRecord(record);
                    }
                }
                int i = customerElectronicCardService.updateCustomerElectronicCard(customerElectronicCard);
                customerCardUseRecord.setOrderNo(orderNo + "2");
                customerCardUseRecord.setCreateTime(new Date());
                customerCardUseRecord.setUsageType("+");
                customerCardUseRecord.setPayType(CustomerCardUseRecord.PAY_TYPE_CONSUME_REF);
                customerCardUseRecord.setId(null);
                customerCardUseRecord.setBalance(customerElectronicCard.getAmt().add(customerElectronicCard.getPresentAmt()).setScale(2, BigDecimal.ROUND_HALF_UP));
                customerCardUseRecordMapper.insertCustomerCardUseRecord(customerCardUseRecord);


                return i;


            } else {
                throw new CustomException("电子卡不存在");
            }

        } else {
            throw new CustomException("电子卡非油品订单暂时无法退款");
        }
    }

    public CustomerElectronicCard dzkRefundGainPresentAmount(CustomerElectronicCard customerElectronicCard, PayOrder payOrder, PresentAmountRecord presentAmountRecord) {
//退送的钱
        BigDecimal presentAmount = presentAmountRecord.getPresentAmount();
        if (presentAmount != null) {
            //Long cecId = presentAmountRecord.getCecId();
            //CustomerElectronicCard customerElectronicCard = customerElectronicCardService.selectCustomerElectronicCard(cecId);
            BigDecimal amt = customerElectronicCard.getAmt();
            // amt=amt.add(payOrder.getAmt());
            if (customerElectronicCard.getPresentAmt() == null) {
                customerElectronicCard.setPresentAmt(BigDecimal.ZERO);
            }

            if (customerElectronicCard.getPresentAmt().compareTo(presentAmount) >= 0) {
                customerElectronicCard.setPresentAmt(customerElectronicCard.getPresentAmt().subtract(presentAmount).setScale(2, BigDecimal.ROUND_HALF_UP));
            } else {
                //会员卡的总赠送金额小于要退返的赠送金额，要扣账户余额
                if (amt.add(customerElectronicCard.getPresentAmt()).setScale(2, BigDecimal.ROUND_HALF_UP).compareTo(presentAmount) < 0) {
                    //如果余额加赠送金额不够扣
                    throw new CustomException("电子卡余额加赠送金额不够扣除");
                } else {
                    //如果够扣除
                    //先从已赠送的金额扣除
                    if (customerElectronicCard.getPresentAmt().compareTo(presentAmount) >= 0) {
                        //如果赠送金额账户够扣除
                        customerElectronicCard.setPresentAmt(customerElectronicCard.getPresentAmt().subtract(presentAmount).setScale(2, BigDecimal.ROUND_HALF_UP));
                    } else {
                        //如果赠送金额账户不够扣除
                        BigDecimal amount = presentAmount.subtract(customerElectronicCard.getPresentAmt()).setScale(2, BigDecimal.ROUND_HALF_UP);
                        customerElectronicCard.setPresentAmt(BigDecimal.ZERO);
                        amt = amt.subtract(amount).setScale(2, BigDecimal.ROUND_HALF_UP);
                        customerElectronicCard.setAmt(amt);
                    }
                }
            }

        }
        return customerElectronicCard;
    }

    public CustomerElectronicCard dzkRefundUsePresentAmount(CustomerElectronicCard customerElectronicCard, PresentAmountRecord presentAmountRecord) {
        //退已经使用的赠送金额到赠送账户
        customerElectronicCard.setPresentAmt(customerElectronicCard.getPresentAmt().add(presentAmountRecord.getPresentAmount()).setScale(2, BigDecimal.ROUND_HALF_UP));
        return customerElectronicCard;
    }

    /**
     * 活动类型
     * AAL：每升立减
     * LOR：按固定数量
     * RFA：按固定金额
     * 订单金额/油机价=升数，然后在对升数立减。支持阶梯????
     * <p>
     * 活动方式
     * RDD：随机立减
     * PAR：百分比立减
     * FAD：定额立减
     *
     * @param amoutv0
     * @param finalDeductionAmount
     * @param reduActiVO
     * @return
     */
    private BigDecimal sumCountActivityMethods(ReductionActivitiesAmtVO amoutv0, BigDecimal finalDeductionAmount, ReduActiVO reduActiVO) {
        ReductionRulesVo reductionRules = new ReductionRulesVo();
        List<ReductionRulesVo> reductionList = new ArrayList<ReductionRulesVo>();
        if (amoutv0.getOilPartOrAll() == 1) {
            //针对全部油品，规则直接关联活动
            reductionRules.setActivityId(amoutv0.getActivityId().longValue());
            reductionList = payOrderMapper.selectReductionRulesList(reductionRules);
        } else {
            //针对部分油品，规则关联油品
            reductionRules.setActivityOilId(new Long(amoutv0.getActivityOilId()));
            reductionList = payOrderMapper.selectReductionRulesList(reductionRules);
        }

        //对活动的具体内容开始计算，判断是哪种活动
        for (ReductionRulesVo rules : reductionList) {
            BigDecimal amtBigd = BigDecimal.ZERO;        //临时金额
            BigDecimal orderLiters = BigDecimal.ZERO;    //加油的升数
            //活动类型
            switch (amoutv0.getActivityType()) {
                case "AAL":
                    log.info("立减活动------每升立减");
                    //每升立减 随机立减（满足x金额才能触发 每升立减活动 随机数在区间内进行随机）
                    //每升立减 百分比立减
                    //每升立减 定额立减
                    finalDeductionAmount = countActivityMethods(rules, amoutv0, reduActiVO, finalDeductionAmount);
                    break;
                case "LOR":
                    //按固定数量 随机立减（满足x金额才能触发 每升立减活动 随机数在区间内进行随机）
                    //按固定数量 百分比立减
                    //按固定数量 定额立减
                    log.info("立减活动------固定数量");
                    switch (amoutv0.getActivityMode()) {
                        case "RDD":
                            Double random = Math.random() * rules.getCutMax() + rules.getCutMin();//随机数
                            if (random > rules.getCutMax()) random = rules.getCutMax();
                            //满足多少升条件则 总共扣除金额=随机立减
                            orderLiters = new BigDecimal(reduActiVO.getOrderLiters());
                            if (orderLiters.compareTo(BigDecimal.valueOf(rules.getFull())) >= 0) {
                                amtBigd = BigDecimal.valueOf(random);
                            }
                            //判断是否超过了活动预算
                            if (new BigDecimal(random).compareTo(amoutv0.getBudget()) == 1) {
                                amtBigd = amoutv0.getBudget().compareTo(BigDecimal.ZERO) == 1 ? amoutv0.getBudget() : BigDecimal.ZERO;
                            }
                            if (finalDeductionAmount.compareTo(amtBigd) == -1) {
                                finalDeductionAmount = amtBigd;
                                reduActiVO.setActivityId(amoutv0.getActivityId().intValue());
                            }
                            break;
                        case "PAR":
                            //满足多少升条件则 总共扣除金额=原始金额*百分比
                            orderLiters = new BigDecimal(reduActiVO.getOrderLiters());
                            if (orderLiters.compareTo(BigDecimal.valueOf(rules.getFull())) >= 0) {
                                amtBigd = BigDecimal.valueOf(rules.getCut()).multiply(BigDecimal.valueOf(0.01)).multiply(reduActiVO.getAmt());
                            }
                            if (finalDeductionAmount.compareTo(amtBigd) == -1) {
                                finalDeductionAmount = amtBigd;
                                reduActiVO.setActivityId(amoutv0.getActivityId().intValue());
                            }
                            break;
                        case "FAD":
                            //满足多少升条件则 总共扣除金额=固定金额
                            orderLiters = new BigDecimal(reduActiVO.getOrderLiters());
                            if (orderLiters.compareTo(BigDecimal.valueOf(rules.getFull())) >= 0) {
                                amtBigd = BigDecimal.valueOf(rules.getCut());
                            }
                            if (finalDeductionAmount.compareTo(amtBigd) == -1) {
                                finalDeductionAmount = amtBigd;
                                reduActiVO.setActivityId(amoutv0.getActivityId().intValue());
                            }
                            break;
                        default:
                            log.info("LOR 没有找到活动方式");
                            break;
                    }
                    break;
                case "RFA":
                    log.info("立减活动------固定金额");
                    //按固定金额 随机立减（满足x金额才能触发 随机数在区间内进行随机）
                    //按固定金额 百分比立减
                    //按固定金额 定额立减
                    amtBigd = BigDecimal.ZERO;
                    orderLiters = BigDecimal.ZERO;
                    switch (amoutv0.getActivityMode()) {
                        case "RDD":
                            log.info("立减活动------随机立减");
                            Double random = Math.random() * rules.getCutMax() + rules.getCutMin();//随机数
                            if (random > rules.getCutMax()) random = rules.getCutMax();
                            if (reduActiVO.getAmt().compareTo(BigDecimal.valueOf(rules.getFull())) >= 0) {
                                amtBigd = BigDecimal.valueOf(random);
                            }
                            //判断是否超过了活动预算
                            if (new BigDecimal(random).compareTo(amoutv0.getBudget()) == 1) {
                                amtBigd = amoutv0.getBudget().compareTo(BigDecimal.ZERO) == 1 ? amoutv0.getBudget() : BigDecimal.ZERO;
                            }
                            if (finalDeductionAmount.compareTo(amtBigd) == -1) {
                                finalDeductionAmount = amtBigd;
                                reduActiVO.setActivityId(amoutv0.getActivityId().intValue());
                            }
                            break;
                        case "PAR":
                            log.info("立减活动------百分比立减");
                            //满足达标金额 总共扣除金额=百分比*原始金额
                            if (reduActiVO.getAmt().compareTo(BigDecimal.valueOf(rules.getFull())) >= 0) {
                                amtBigd = reduActiVO.getAmt().multiply(BigDecimal.valueOf(0.01)).multiply(BigDecimal.valueOf(rules.getCut()));
                            }
                            if (finalDeductionAmount.compareTo(amtBigd) == -1) {
                                finalDeductionAmount = amtBigd;
                                reduActiVO.setActivityId(amoutv0.getActivityId().intValue());
                            }
                            break;
                        case "FAD":
                            log.info("立减活动------定额立减");
                            //满足达标金额总共扣除金额=定额
                            if (reduActiVO.getAmt().compareTo(BigDecimal.valueOf(rules.getFull())) >= 0) {
                                amtBigd = BigDecimal.valueOf(rules.getCut());
                            }
                            if (finalDeductionAmount.compareTo(amtBigd) == -1) {
                                finalDeductionAmount = amtBigd;
                                reduActiVO.setActivityId(amoutv0.getActivityId().intValue());
                            }
                            break;
                        default:
                            log.info("RFA 没有找到活动方式");
                            break;
                    }
                    break;
                default:
                    log.info("没有找到活动类型");
                    break;
            }
        }
        return finalDeductionAmount;
    }

    /**
     * //每升立减 随机立减（满足x金额才能触发 每升立减活动 随机数在区间内进行随机）
     * //每升立减 百分比立减
     * //每升立减 定额立减
     * TODO 后续优化可使用设计模式
     * 计算活动方式能被抵扣的金额，获取最大抵扣额度
     *
     * @param rules
     * @param amoutv0
     * @param reduActiVO
     * @param amtBig
     * @return
     */
    private BigDecimal countActivityMethods(ReductionRulesVo rules, ReductionActivitiesAmtVO amoutv0,
                                            ReduActiVO reduActiVO, BigDecimal amtBig) {
        BigDecimal amtBigd = BigDecimal.ZERO;
        switch (amoutv0.getActivityMode()) {
            case "RDD":
                Double random = Math.random() * rules.getCutMax() + rules.getCutMin();//随机数
                if (random > rules.getCutMax()) random = rules.getCutMax();
//			if(random < rules.getCutMin()) random = rules.getCutMin();
                //每升立减活动（满足x金额才能触发 每升立减活动 随机数在区间内进行随机）
                if (reduActiVO.getAmt().compareTo(BigDecimal.valueOf(rules.getFull())) >= 0) {
                    amtBigd = new BigDecimal(reduActiVO.getOrderLiters()).setScale(0, BigDecimal.ROUND_DOWN).multiply(BigDecimal.valueOf(random));
                }

                //判断是否超过了活动预算
                if (new BigDecimal(random).compareTo(amoutv0.getBudget()) == 1) {
                    amtBigd = amoutv0.getBudget().compareTo(BigDecimal.ZERO) == 1 ? amoutv0.getBudget() : BigDecimal.ZERO;
                }

                if (amtBig.compareTo(amtBigd) == -1) {
                    amtBig = amtBigd;
                    reduActiVO.setActivityId(amoutv0.getActivityId().intValue());
                }
                break;
            case "PAR":
                //总共扣除金额=百分比*单价
                //计算单价=总金额/总升
                if (rules.getFull() == null || reduActiVO.getAmt().compareTo(BigDecimal.valueOf(rules.getFull())) >= 0) {
                    amtBigd = reduActiVO.getAmt().multiply(BigDecimal.valueOf(rules.getCut())).multiply(BigDecimal.valueOf(0.01)).setScale(2, RoundingMode.DOWN);
                    if (amtBig.compareTo(amtBigd) == -1) {
                        amtBig = amtBigd;
                        reduActiVO.setActivityId(amoutv0.getActivityId().intValue());
                    }
                }
                break;
            case "FAD":
                //总共扣除金额=每升*定额
                if (rules.getFull() == null || reduActiVO.getAmt().compareTo(BigDecimal.valueOf(rules.getFull())) >= 0) {
                    amtBigd = new BigDecimal(reduActiVO.getOrderLiters()).multiply(BigDecimal.valueOf(rules.getCut()));
                    if (amtBig.compareTo(amtBigd) == -1) {
                        amtBig = amtBigd;
                        reduActiVO.setActivityId(amoutv0.getActivityId().intValue());
                    }
                }
                break;
            default:
                log.info("AAL 未查询到活动方式");
                break;
        }
        return amtBig;
    }

    @Override
    public PayOrder timeSetting(PayOrder payOrder,Long stationId) {
        Station station = stationMapper.selectStationById(stationId);
        if (payOrder.getBeginPayTime() != null && payOrder.getEndPayTime() != null) {
        if (payOrder.getBeginTime() == "" && payOrder.getEndTime() == "") {
            payOrder.setBeginTime(payOrder.getBeginPayTime());
            payOrder.setEndTime(payOrder.getEndPayTime());
        }
        }
        LoginUser current = SecurityUtils.getLoginUser();
        SysUser isStaff =  current.getUser();
        // 角色为员工标识
        boolean staff = StaffUtil.isStaff(isStaff);
if(staff){
    return  payOrder;
}
        String newStartTime = "";
        String newEndTime = "";
        LocalDate today = LocalDate.now(); // 当前日期
        LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式
        String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串
        newEndTime=endTimeStr;
        if (station.getDefaultTimePeriodOrder().equals("all")) {
            // 开始时间和结束时间为空的逻辑
            LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期
            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
// 将开始时间和结束时间的字符串赋值给相应的变量
            newStartTime=beginTimeStr;

        } else if (station.getDefaultTimePeriodOrder().equals("today")) {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY, 0); // 设置小时为0
            cal.set(Calendar.MINUTE, 0); // 设置分钟为0
            cal.set(Calendar.SECOND, 0); // 设置秒为0
            cal.set(Calendar.MILLISECOND, 0); // 设置毫秒为0

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            newStartTime = sdf.format(cal.getTime()); // 将当天的0点0分0秒转换为字符串并设置为开始时间
        } else if (station.getDefaultTimePeriodOrder().equals("last_half_hour")) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MINUTE, -30); // 减去30分钟
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            newStartTime = sdf.format(cal.getTime());
        } else if (station.getDefaultTimePeriodOrder().equals("last_hour")) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.HOUR, -1); // 减去1小时
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            newStartTime = sdf.format(cal.getTime());
        } else if (station.getDefaultTimePeriodOrder().equals("last_shift_time")) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("stationId", stationId);
            Map<String, Object>     endTimeMap = classSettlementMapper.queryLastEndTime(params);
            if (endTimeMap != null && !endTimeMap.isEmpty()
                    && Objects.nonNull(endTimeMap.get("classEndTime"))) {
                newStartTime = (DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", (Date) endTimeMap.get("classStartTime")));

            }

            // 实现根据班次时间计算开始时间的逻辑并设置给 payOrder
        } else if (station.getDefaultTimePeriodOrder().equals("last_shift_time_end")) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("stationId", stationId);
            Map<String, Object>     endTimeMap = classSettlementMapper.queryLastEndTime(params);
            if (endTimeMap != null && !endTimeMap.isEmpty()
                    && Objects.nonNull(endTimeMap.get("classEndTime"))) {
                newStartTime = (DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", (Date) endTimeMap.get("classEndTime")));

            }

            // 实现根据班次结束时间计算开始时间的逻辑并设置给 payOrder
        }


        // 判断startTime是否有数据
        if (payOrder.getBeginTime() != null && !payOrder.getBeginTime().isEmpty()) {
            // 判断 station.getShowHistoricalOrders() 是否为 1
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
            if (station.getShowHistoricalOrders() == 1 && !newStartTime.equals("")) {
                Date existingStartTime = sdf.parse(payOrder.getBeginTime());
                Date currentStartTime = sdf.parse(newStartTime);

                // 判断 cal.getTime() 是否在原来的 startTime 之后
                if (currentStartTime.after(existingStartTime)) {
                    payOrder.setBeginTime(sdf.format(currentStartTime)) ;
                }
            }
        } catch (ParseException e) {
            // 处理解析异常
            e.printStackTrace(); // 可以根据需要处理异常
        }
        } else {
            if(!newStartTime.equals("")){
                payOrder.setBeginTime(newStartTime) ;
                payOrder.setEndTime(newEndTime) ;
            }
        }


        return payOrder;
    }


    @Override
    public ClassSettlement classSettlementtimeSetting(ClassSettlement classSettlement,Long stationId) {
        Station station = stationMapper.selectStationById(stationId);
        LoginUser current = SecurityUtils.getLoginUser();
        SysUser isStaff =  current.getUser();
        // 角色为员工标识
        boolean staff = StaffUtil.isStaff(isStaff);
        if(staff){
            return  classSettlement;
        }
        String newStartTime = "";
        String newEndTime = "";
        LocalDate today = LocalDate.now(); // 当前日期
        LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式
        String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串
        newEndTime=endTimeStr;
        if (station.getDefaultTimePeriodClass().equals("all")) {
            // 开始时间和结束时间为空的逻辑
            LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期
            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
// 将开始时间和结束时间的字符串赋值给相应的变量
            newStartTime=beginTimeStr;
        } else if (station.getDefaultTimePeriodClass().equals("today")) {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY, 0); // 设置小时为0
            cal.set(Calendar.MINUTE, 0); // 设置分钟为0
            cal.set(Calendar.SECOND, 0); // 设置秒为0
            cal.set(Calendar.MILLISECOND, 0); // 设置毫秒为0

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            newStartTime = sdf.format(cal.getTime()); // 将当天的0点0分0秒转换为字符串并设置为开始时间
        } else if (station.getDefaultTimePeriodClass().equals("last_half_hour")) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MINUTE, -30); // 减去30分钟
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            newStartTime = sdf.format(cal.getTime());
        } else if (station.getDefaultTimePeriodClass().equals("last_hour")) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.HOUR, -1); // 减去1小时
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            newStartTime = sdf.format(cal.getTime());
        }else if (station.getDefaultTimePeriodClass().equals("week")) {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 设置为本周的星期一
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            newStartTime = sdf.format(cal.getTime());
        } else if (station.getDefaultTimePeriodClass().equals("month")) {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.DAY_OF_MONTH, 1);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            newStartTime = sdf.format(cal.getTime());
        } else if (station.getDefaultTimePeriodClass().equals("last_shift_time")) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("stationId", stationId);
            Map<String, Object>     endTimeMap = classSettlementMapper.queryLastEndTime(params);
            if (endTimeMap != null && !endTimeMap.isEmpty()
                    && Objects.nonNull(endTimeMap.get("classEndTime"))) {
                newStartTime = (DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", (Date) endTimeMap.get("classEndTime")));

            }

            // 实现根据班次结束时间计算开始时间的逻辑并设置给 payOrder
        }


        // 判断startTime是否有数据
        if (classSettlement.getBeginTime() != null && !classSettlement.getBeginTime().isEmpty()) {
            // 判断 station.getShowHistoricalClass() 是否为 1
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                if (station.getShowHistoricalClass() == 1 && !newStartTime.equals("")) {
                    Date existingStartTime = sdf.parse(classSettlement.getBeginTime());
                    Date currentStartTime = sdf.parse(newStartTime);

                    // 判断 cal.getTime() 是否在原来的 startTime 之后
                    if (currentStartTime.after(existingStartTime)) {
                        classSettlement.setBeginTime(sdf.format(currentStartTime)) ;
                    }
                }
            } catch (ParseException e) {
                // 处理解析异常
                e.printStackTrace(); // 可以根据需要处理异常
            }
        } else {
            if(!newStartTime.equals("")){
                classSettlement.setBeginTime(newStartTime) ;
                classSettlement.setEndTime(newEndTime) ;
            }
        }


        return classSettlement;
    }


    @Override
    public List<StatisticsPayOrder> selectRegionalReport(RegionalReportDto regionalReportDto) {
        List<StatisticsPayOrder> statisticsPayOrders = payOrderMapper.selectRegionalReport(regionalReportDto);

        for (StatisticsPayOrder statisticsPayOrder : statisticsPayOrders) {
            String district = memberManagementService.getDistrictByEnterpriseId(statisticsPayOrder.getEnterpriseId());
            if (StringUtils.isNotBlank(district)) {
                statisticsPayOrder.setDistrict(district);
            }
        }
        return statisticsPayOrders;
    }

    @Override
    public List<OilSaleNumDto> getOilSaleNumList(PayOrder payOrder) {
        List<OilSaleNumDto> oilSaleNumList = new ArrayList<>();
        List<PayOrder> payOrderList = payOrderMapper.getOilSaleNumList(payOrder);
        List<PayOrder> historyPayOrderList = payOrderHistoryMapper.getOilSaleNumList(payOrder);

        if (CollectionUtils.isEmpty(payOrderList) && CollectionUtils.isEmpty(historyPayOrderList)) {
            return oilSaleNumList;
        }

        if (CollectionUtils.isNotEmpty(payOrderList) && CollectionUtils.isEmpty(historyPayOrderList)) {
            for (PayOrder order : payOrderList) {
                if (Objects.nonNull(order)) {
                    OilSaleNumDto oilSaleNumDto = new OilSaleNumDto();
                    BeanUtils.copyProperties(order, oilSaleNumDto);
                    oilSaleNumList.add(oilSaleNumDto);
                }
            }
            return oilSaleNumList;
        }

        if (CollectionUtils.isEmpty(payOrderList) && CollectionUtils.isNotEmpty(historyPayOrderList)) {
            for (PayOrder order : historyPayOrderList) {
                if (Objects.nonNull(order)) {
                    OilSaleNumDto oilSaleNumDto = new OilSaleNumDto();
                    BeanUtils.copyProperties(order, oilSaleNumDto);
                    oilSaleNumList.add(oilSaleNumDto);
                }
            }
            return oilSaleNumList;
        }

        payOrderList.stream().forEach(order -> {
            for (PayOrder historyOrder : historyPayOrderList) {
                if (StringUtils.isNotEmpty(order.getOilName()) && StringUtils.isNotEmpty(historyOrder.getOilName())
                        && order.getOilName().equals(historyOrder.getOilName())) {
                    OilSaleNumDto oilSaleNumDto = new OilSaleNumDto();
                    oilSaleNumDto.setOilName(order.getOilName());
                    oilSaleNumDto.setOrderLiters((order.getOrderLiters() != null ? order.getOrderLiters() : BigDecimal.ZERO)
                            .add(historyOrder.getOrderLiters() != null ? historyOrder.getOrderLiters() : BigDecimal.ZERO));
                    oilSaleNumList.add(oilSaleNumDto);
                }
            }
        });
        return oilSaleNumList;
    }

    @Override
    public List<YunHuaOrderInfo> selectPayOrderListByStartTime(String startTime) {
        return payOrderMapper.getOrderListByDate(startTime);
    }

    @Override
    public String getOrderStatus(YunHuaOrderInfo yunHuaOrderInfo) {
        try {

            PayWay payWay = payWayMapper.selectPayWayById(Long.valueOf(yunHuaOrderInfo.getPayWayId()));
            log.info("订单支付渠道信息【{}】", payWay);
            //只处理云化支付
            if (!"5".equals(payWay.getPayType())) {
                return "";
            }
            yunHuaOrderInfo.setMno(payWay.getMno());
            Sha256SignCreator sha256SignCreator = new Sha256SignCreator();
            String sign = sha256SignCreator.encode(JSONObject.parseObject(yunHuaOrderInfo.toBeforeRequest()), payWay.getSecretKey());
            yunHuaOrderInfo.setSign(sign);

            String mmmmm = yunHuaOrderInfo.toAfterRequest();
            log.info("查询云化订单支付状态,参数【{}】，请求地址【{}】", mmmmm, yunHuaOrderQueryUrl);
            String res = com.qujia.station.utils.HttpUtils.connectPostUrl(yunHuaOrderQueryUrl, mmmmm);
            log.info("查询订单状态返回值【{}】", res);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    @Transactional
    public void refundPresent(String orderNo) {
        //退积分
        PayOrder payOrder = payOrderMapper.selectOrderInfoByOrdNo(orderNo);
        if (payOrder == null) {
            return;
        }
        //退已经使用的优惠券
        String discountCoupon = payOrder.getDiscountCoupon();
        if (StringUtils.isNotEmpty(discountCoupon)) {
            CouponUser couponUser = new CouponUser();
            couponUser.setId(Integer.parseInt(discountCoupon));
            couponUser.setCouponIsUsed("0");
            couponUserMapper.updateCouponUser(couponUser);
        }

        SysAppUserInfo appUserInfo = new SysAppUserInfo();
        appUserInfo.setMobilePhone(payOrder.getCustomerPhone());
        appUserInfo.setStationId(payOrder.getEnterpriseId());
        List<SysAppUserInfo> sysAppUserInfos = appUserInfoMapper.selectList(appUserInfo);
        if (sysAppUserInfos.size() == 0) {
            return;
        }
        appUserInfo = sysAppUserInfos.get(0);
        CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
        customerPointsRecord.setOrderNo(orderNo);
        customerPointsRecord.setRecordType("+");
        List<CustomerPointsRecord> customerPointsRecords = customerPointsRecordMapper.selectCustomerPointsRecordList(customerPointsRecord);
        if (customerPointsRecords.size() > 0) {
            //退积分
            customerPointsRecord = customerPointsRecords.get(0);
            Long integral = appUserInfo.getIntegral() - customerPointsRecord.getIntegral();
            if (integral < 0) {
                //integral=0l;
                throw new CustomException("账户积分不够回退，不能退款");
            }
            appUserInfo.setIntegral(integral);

            customerPointsRecord.setId(null);
            customerPointsRecord.setRecordType("-");
            customerPointsRecord.setCreateTime(new Date());
            customerPointsRecord.setAction("退款");
            customerPointsRecordMapper.insertCustomerPointsRecord(customerPointsRecord);
            customerPointsRecordService.wxgzhIntegralPush(customerPointsRecord);
        }
        //退成长值
        Long growthValue = payOrder.getGrowthValue();
        if (growthValue != null && growthValue > 0) {
            Long growUpValue = appUserInfo.getGrowUpValue();
            if (growUpValue == null) {
                growUpValue = 0l;
            }
            growUpValue = growUpValue - growthValue;
            if (growUpValue < 0) {
                growUpValue = 0l;
            }
            appUserInfo.setGrowUpValue(growUpValue);
        }
        appUserInfoMapper.updateAppUserInfo(appUserInfo);
        //退优惠券
        PresentCouponUserRecord presentCouponUserRecord = new PresentCouponUserRecord();
        presentCouponUserRecord.setOrderNo(orderNo);
        presentCouponUserRecord.setBusinessName("pay_order");
        List<PresentCouponUserRecord> couponUserRecords = presentCouponUserRecordMapper.query(presentCouponUserRecord);

        for (PresentCouponUserRecord couponUserRecord : couponUserRecords) {
            CouponUser cu = couponUserMapper.selectCouponUserById(couponUserRecord.getCouponUserId().intValue());
            if (cu != null && cu.getCouponIsUsed().equals("1")) {
                throw new CustomException("消费赠送的优惠券已有被使用，不能退款");
            }

            CouponUser couponUser = new CouponUser();
            couponUser.setId(couponUserRecord.getCouponUserId().intValue());
            couponUser.setIsDeleted("1");
            couponUserMapper.updateCouponUser(couponUser);
            couponUser = couponUserMapper.selectCouponUserById(couponUserRecord.getCouponUserId().intValue());
            Long couponId = couponUser.getCouponId();
            CouponInfo couponInfo = couponInfoMapper.selectCouponInfoById(couponId.intValue());
            //退优惠券次数
            Integer getCouponNum = couponInfo.getGetCouponNum() - 1;
            if (getCouponNum < 0) {
                getCouponNum = 0;
            }
            couponInfo.setGetCouponNum(getCouponNum);
            couponInfoMapper.updateCouponInfo(couponInfo);
            if (StringUtils.isNotEmpty(couponUser.getMobilePhone()) && StringUtils.isNotEmpty(couponUser.getIssueId())) {
                int i = couponUserMapper.deleteUserGiveCountByPhoneAndIssueId(couponUser.getMobilePhone(), couponUser.getIssueId());
            }
        }
        //退立减次数
        payOrderMapper.deleteReductionActivityLogByOrderId(payOrder.getOrderId());

    }

    @Override
    public List<PayOrder> getPayOrderListByOrderMergeNo(String orderMergeNo) {
        return payOrderMapper.getPayOrderListByOrderMergeNo(orderMergeNo);
    }

    @Transactional
    @Override
    public int examinRefundSuccess(PayOrder payOrderThis, LoginUser user) {
        int i = 0;
        List<PayOrder> payOrderList = new ArrayList<>();
        payOrderList.add(payOrderThis);
        try {
            if (payOrderThis.getOrderMergeNo() != null) {
                payOrderList = getPayOrderListByOrderMergeNo(payOrderThis.getOrderMergeNo());
            }
            for (PayOrder order : payOrderList) {
                examinRefundSuccessMain(order, user);
                i++;
            }
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }
        return i;
    }

    private void examinRefundSuccessMain( PayOrder payOrder1, LoginUser user){
        payOrder1.setExaminUser(user.getUser().getUserId());
        payOrder1.setExaminDate(new Date());
        payOrder1.setExaminStatus("2");

        try {
            //现金退款不走接口
            if ("xj".equals(payOrder1.getPayType())) {
                log.debug("现金退款");
                payOrder1.setRefundSuccessDate(new Date());
                payOrder1.setStatus("3");
                payOrder1.setExaminDate(new Date());
                payOrder1.setExaminStatus("2");
                updatePayOrder(payOrder1);
            } else if ("dzk".equals(payOrder1.getPayType())) {
                refundPresent(payOrder1.getOrderNo());
                dzkRefund(payOrder1);
                payOrder1.setRefundSuccessDate(new Date());
                payOrder1.setStatus("3");
                payOrder1.setExaminDate(new Date());
                payOrder1.setExaminStatus("2");
                updatePayOrder(payOrder1);
                orderPrintService.printRefundOrder(payOrder1);
                UniversalRedisMessageDto dto = new UniversalRedisMessageDto();
                dto.setData(JSONObject.toJSONString(payOrder1));
                dto.setMessageType(WxConsumptionMessageEnum.REFUND_MESSAGE_PUSH.getValue());
                dto.setTitle(WxConsumptionMessageEnum.REFUND_MESSAGE_PUSH.getKey());

                redisTemplate.convertAndSend(channel, dto);
            } else {
                refundPresent(payOrder1.getOrderNo());
                AjaxResult ajaxResult = sxfRefund(payOrder1);
                payOrder1.setRefundSuccessDate(new Date());
                payOrder1.setStatus("3");
                payOrder1.setExaminDate(new Date());
                payOrder1.setExaminStatus("2");
                updatePayOrder(payOrder1);
                UniversalRedisMessageDto dto = new UniversalRedisMessageDto();
                dto.setData(JSONObject.toJSONString(payOrder1));
                dto.setMessageType(WxConsumptionMessageEnum.REFUND_MESSAGE_PUSH.getValue());
                dto.setTitle(WxConsumptionMessageEnum.REFUND_MESSAGE_PUSH.getKey());
                redisTemplate.convertAndSend(channel, dto);
            }
        } catch (Exception e) {
            payOrder1.setStatus(null);
            //设置为退款失败的状态
            payOrder1.setExaminStatus("4");
            payOrderService.updatePayOrder(payOrder1);
            if (e.getMessage().contains("账户积分不够回退，不能退款")) {
                throw new CustomException("账户积分不够回退，不能退款");
            }
            if (e.getMessage().contains("消费赠送的优惠券已有被使用，不能退款")) {
                throw new CustomException("消费赠送的优惠券已有被使用，不能退款");
            }
        }
    }

}
